package com.cac.demo.newCode.cemop.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cac.demo.controller.compressedFiles.CompressedFilesEditor;
import com.cac.demo.dao.itemOutBill.ItemInventoryOutbillDao;
import com.cac.demo.dao.materialScan.WmsDeliverPlanDao;
import com.cac.demo.dao.msDeliveryCrew.MsDeliveryCrewDao;
import com.cac.demo.newCode.cemop.dto.*;
import com.cac.demo.newCode.cemop.enums.CemopEnum;
import com.cac.demo.newCode.cemop.enums.CemopXmlEnum;
import com.cac.demo.newCode.cemop.enums.DeliveryStatusEnum;
import com.cac.demo.newCode.cemop.mapper.CemopMapper;
import com.cac.demo.newCode.cemop.service.CemopService;
import com.cac.demo.newCode.cemop.utils.CemopUtil;
import com.cac.demo.newCode.cemop.utils.CemopXmlUtil;
import com.cac.demo.newCode.cemop.utils.SQLiteUtil;
import com.cac.demo.newCode.cemop.vo.*;
import com.cac.demo.newCode.interfaceLog.entity.InterfaceLog;
import com.cac.demo.newCode.interfaceLog.service.InterfaceLogService;
import com.cac.demo.newCode.materialStorage.entity.*;
import com.cac.demo.newCode.materialStorage.service.*;
import com.cac.demo.newCode.sorting.entity.*;
import com.cac.demo.newCode.sorting.mapper.*;
import com.cac.demo.newCode.sorting.service.*;
import com.cac.demo.newCode.sorting.utils.IPUtils;
import com.cac.demo.service.gkinterface.WorkService;
import com.cac.demo.service.itemOutBill.ItemOutBillService;
import com.cac.demo.service.materialScan.WmsDeliverPlanService;
import com.cac.demo.service.msTaskAo.MsTaskAoService;
import com.cac.demo.service.outBill.WmsInvOutBillService;
import com.cac.demo.util.AccessLog;
import com.cac.demo.util.XmlReadUtil;
import com.cac.demo.util.adapter.ComUtil;
import com.cac.demo.util.adapter.ResponseMsg;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CemopServiceImpl implements CemopService {

    @Autowired
    private Environment environment;
    @Resource
    CemopUtil cemopUtil;
    @Resource
    private SQLiteUtil sqliteUtil;
    @Resource
    private WmsDeliverPlanDao wmsDeliverPlanDao;
    @Resource
    private WmsDeliverPlanService wmsDeliverPlanService;
    @Resource
    CemopMapper cemopMapper;
    @Resource
    IWmsItemInventoryService wmsItemInventoryService;
    @Resource
    IMsWorkbinMaterialService workbinMaterialService;
    @Resource
    IMsErpOutBillService msErpOutBillService;

    @Resource
    IWmsReturnApplyService wmsReturnApplyService;
    @Resource
    IWmsDeliveryPlanService wmsDeliveryPlanService;
    @Autowired
    private CompressedFilesEditor compressedFilesEditor;
    @Resource
    private MsDeliveryCrewDao msDeliveryCrewDao;
    @Resource
    private CemopXmlUtil cemopXmlUtil;
    @Resource
    private IMsAoMatchInfoNewService iMsAoMatchInfoNewService;
    @Resource
    private MsSecondMatchInfoService msSecondMatchInfoService;
    @Resource
    private MsAoMatchBillMapper msAoMatchBillMapper;
    @Resource
    private IMsAoMatchBillService iMsAoMatchBillService;
    @Resource
    private IWmsInvOutAllotmentService iWmsInvOutAllotmentService;
    @Resource
    private IWmsItemTransactionService iWmsItemTransactionService;
    @Resource
    private IWmsInvOutBillHService iWmsInvOutBillHService;
    @Resource
    private IWmsInvOutBillLService iWmsInvOutBillLService;
    @Resource
    private WmsInvOutBillService wmsInvOutBillService;
    @Resource
    private IWmsReturnApplyService iWmsReturnApplyService;
    @Resource
    private InterfaceLogService interfaceLogService;
    @Autowired
    private ItemOutBillService itemOutBillService;
    @Autowired
    private ItemInventoryOutbillDao itemInventoryOutbillDao;
    @Resource
    private WmsInvOutBillHMapper wmsInvOutBillHMapper;
    @Resource
    private MsTaskAoMapper msTaskAoMapper;
    @Resource
    private IMsTaskAoService iMsTaskAoService;
    @Resource
    private MsAoMatchInfoMapper msAoMatchInfoMapper;


    private JSONObject jsonToObject = new JSONObject();
    private WmsReturnApply wmsReturnApply;

    @Transactional
    @AccessLog(LogType = "CEMOP系统退库单接收或驳回通知101库存数据", sendOrReceive = "send")
    @Override
    public ResponseMsg<Object> getReturnOrderData(JSONObject jsonObject) {
        jsonObject.put("description","CEMOP系统退库单接收或驳回");
        log.info("CEMOP系统退库单接收或驳回通知101库存数据" + jsonObject);
        try {
            //获取cemop文件
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.RETURN_ORDER.getCode());
            List<CemopReturnOrderDTO> cemopReturnOrderDTOList = cemopDownDTO.getCemopReturnOrderDTOList();
            log.info("解析文件后数据" + cemopReturnOrderDTOList.toString());
            ArrayList<WmsReturnApply> wmsReturnApplies = new ArrayList<>();
            //组装成Entity操作系统数据
            for (CemopReturnOrderDTO cemopReturnOrderDTO : cemopReturnOrderDTOList) {
                WmsReturnApply wmsReturnApply = new WmsReturnApply();
                wmsReturnApply.setRejectEmpCode(cemopReturnOrderDTO.getUserId());
                wmsReturnApply.setRejectReason(cemopReturnOrderDTO.getTurndnReasDesc());
                wmsReturnApply.setReturnStatus(cemopReturnOrderDTO.getStatus());
                wmsReturnApplies.add(wmsReturnApply);
                LambdaUpdateWrapper<WmsReturnApply> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(WmsReturnApply::getWmsReturnApplyId,cemopReturnOrderDTO.getMomWmsReturnApplyId());
                wmsReturnApplyService.update(wmsReturnApply,updateWrapper);
                if(cemopReturnOrderDTO.getStatus().equals("ó")) {
                    LambdaQueryWrapper<WmsReturnApply> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WmsReturnApply::getWmsReturnApplyId, cemopReturnOrderDTO.getMomWmsReturnApplyId());
                    WmsReturnApply wmsReturnApply1 = iWmsReturnApplyService.getOne(queryWrapper);
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    map1.put("wmsReturnApplyId", cemopReturnOrderDTO.getMomWmsReturnApplyId());
                    map1.put("billNo", wmsReturnApply1.getBillNo());
                    map1.put("productCode", wmsReturnApply1.getProductCode());
                    map1.put("batchNo", wmsReturnApply1.getBatchNo());
                    map1.put("itemCode", wmsReturnApply1.getItemCode());
                    map1.put("qualityCode", wmsReturnApply1.getQualityCode());
                    map1.put("wmsDeliveryPlanId", wmsReturnApply1.getWmsDeliveryPlanId());
                    map1.put("returnQty", wmsReturnApply1.getReturnQty());
                    //对出库单主表子表及库身事务表进行数据播入
                    wmsInvOutBillService.insertWmsInvOutBillHMany(map1);
                    //更新台账表信息
                    itemOutBillService.updateWmsItemInventory(map1);
                    String wmsReturnApplyId = (String) map1.get("wmsReturnApplyId");
                    //判断已经退库的数量，若为零，则将退库状态改为结束
                    Integer notReturnQty = itemOutBillService.notReturnQtySearch(wmsReturnApplyId);
                    if (notReturnQty <= 0) {
                        itemOutBillService.returnStatusUp(wmsReturnApplyId);
                        //修改交接单状态
                        itemInventoryOutbillDao.updateDeliveryPlan(map1);
                    }
                }
            }
            log.info("处理完成后的退库单数据" + wmsReturnApplies.toString());
            log.info("CEMOP系统退库单接收或驳回通知101库存成功" + jsonObject);
            jsonObject.put("msg","CEMOP系统退库单接收或驳回通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonObject).setMessage("CEMOP系统退库单接收或驳回通知101库存成功！");
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * CEMOP系统出库台账通知101库存
     *
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> getOutboundData(JSONObject jsonObject) {
        log.info("CEMOP系统出库台账通知101库存数据" + jsonObject);
        jsonObject.put("description","CEMOP系统出库台账");
        try {
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.OUTBOUND.getCode());
            List<CemopOutboundDTO> cemopOutboundDTOS = cemopDownDTO.getCemopOutboundDTOS();
            log.info("解析文件后数据" + cemopOutboundDTOS.toString());
            CemopOutboundDTO cemopOutboundDTO = cemopOutboundDTOS.get(0);
            //查询存在的台账不存在的存日志
            WmsItemInventory wmsItemInventory = wmsItemInventoryService.getById(cemopOutboundDTO.getMomWmsItemInventoryId());
            log.info("查询出的台账信息" + wmsItemInventory);
            if (wmsItemInventory == null) {
                //存在处理数据
                //查询CEMOP出库的缓存箱以及出库的数量(存在单个缓存箱大于出库数量)
                LambdaQueryWrapper<MsWorkbinMaterial> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(MsWorkbinMaterial::getWmsItemInventoryId, cemopOutboundDTO.getMomWmsItemInventoryId());
                queryWrapper.ge(MsWorkbinMaterial::getItemQty, cemopOutboundDTO.getOutQty());
                queryWrapper.isNotNull(MsWorkbinMaterial::getWorkbinCode);
                queryWrapper.last("AND ROWNUM = 1");
                MsWorkbinMaterial msWorkbinMaterial = workbinMaterialService.getOne(queryWrapper);
                log.info("查询CEMOP出库的缓存箱以及出库的数量(存在单个缓存箱大于出库数量)" + msWorkbinMaterial);
                if (msWorkbinMaterial == null) {
                    //查询CEMOP出库的缓存箱以及出库的数量(单个缓存箱数量小于出库数量)
                    LambdaQueryWrapper<MsWorkbinMaterial> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(MsWorkbinMaterial::getWmsItemInventoryId, cemopOutboundDTO.getMomWmsItemInventoryId());
                    queryWrapper1.le(MsWorkbinMaterial::getItemQty, cemopOutboundDTO.getOutQty());
                    queryWrapper1.orderByDesc(MsWorkbinMaterial::getItemQty);
                    List<MsWorkbinMaterial> list = workbinMaterialService.list(queryWrapper1);
                    log.info("查询CEMOP出库的缓存箱以及出库的数量(单个缓存箱数量小于出库数量)" + list);
                    //定义需要出库的数量
                    BigDecimal outQty = new BigDecimal(cemopOutboundDTO.getOutQty());
                    //循环去减库存
                    for (MsWorkbinMaterial workbinMaterial : list) {
                        //获取当前库存
                        BigDecimal itemQty = workbinMaterial.getItemQty();
                        //出库数量-库存数量
                        outQty = outQty.subtract(itemQty);
                        MsErpOutBill msErpOutBill = new MsErpOutBill();
                        if (outQty.compareTo(BigDecimal.ZERO) >= 0) {
                            //没有扣完或者刚好扣完则执行
                            //更新库存表
                            workbinMaterial.setItemQty(BigDecimal.valueOf(0));
                            workbinMaterial.setErpoutQty(workbinMaterial.getErpoutQty().add(itemQty));
                            //保存需要出库的erp缓存箱数据
                            msErpOutBill.setErpOutQty(itemQty);
                        } else if (outQty.compareTo(BigDecimal.ZERO) < 0) {
                            //扣成负数了就直接取反数则为剩余库存
                            BigDecimal negate = outQty.negate();
                            //存在库存减去剩余库存则为出库数量
                            BigDecimal subtract = itemQty.subtract(negate);
                            workbinMaterial.setItemQty(negate);
                            msErpOutBill.setErpOutQty(subtract);
                        }
                        log.info("修改缓存箱数据扣掉库存");
                        workbinMaterialService.updateById(workbinMaterial);
                        msErpOutBill.setMsErpOutBillId(ComUtil.getId());
                        msErpOutBill.setWmsItemInventoryId(cemopOutboundDTO.getMomWmsItemInventoryId());
                        msErpOutBill.setWmsItemTransactionId(cemopOutboundDTO.getMomWmsItemTransactionId());
                        msErpOutBill.setMsWorkbinMaterialId(workbinMaterial.getMsWorkbinMaterialId());
                        msErpOutBill.setIsValid("Y");
                        msErpOutBill.setCreationDate(new Date());
                        msErpOutBill.setWorkbinCode(msWorkbinMaterial.getWorkbinCode());
                        log.info("保存需要出库的CEMOP缓存箱数据");
                        msErpOutBillService.save(msErpOutBill);
                    }
                } else {
                    BigDecimal outQty = new BigDecimal(cemopOutboundDTO.getOutQty());
                    BigDecimal subtract = msWorkbinMaterial.getItemQty().subtract(outQty);
                    msWorkbinMaterial.setItemQty(subtract);
                    msWorkbinMaterial.setErpoutQty(outQty);
                    workbinMaterialService.updateById(msWorkbinMaterial);
                    log.info("修改缓存箱数据扣掉库存");
                    MsErpOutBill msErpOutBill = new MsErpOutBill();
                    msErpOutBill.setErpOutQty(subtract);
                    msErpOutBill.setMsErpOutBillId(ComUtil.getId());
                    msErpOutBill.setWmsItemInventoryId(cemopOutboundDTO.getMomWmsItemInventoryId());
                    msErpOutBill.setWmsItemTransactionId(cemopOutboundDTO.getMomWmsItemTransactionId());
                    msErpOutBill.setMsWorkbinMaterialId(msWorkbinMaterial.getMsWorkbinMaterialId());
                    msErpOutBill.setIsValid("Y");
                    msErpOutBill.setCreationDate(new Date());
                    msErpOutBill.setWorkbinCode(msWorkbinMaterial.getWorkbinCode());
                    log.info("保存需要出库的CEMOP缓存箱数据");
                    msErpOutBillService.save(msErpOutBill);
                }
                wmsItemInventory.setCurrentOnhandQty(wmsItemInventory.getCurrentOnhandQty().subtract(new BigDecimal(cemopOutboundDTO.getOutQty())));
                wmsItemInventory.setEngagedQty(wmsItemInventory.getEngagedQty().subtract(new BigDecimal(cemopOutboundDTO.getOutQty())));
                wmsItemInventoryService.updateById(wmsItemInventory);
            } else {
                log.info("系统不存在该台账");
            }
            log.info("CEMOP系统出库台账通知101库存成功" + jsonObject);
            jsonObject.put("msg","CEMOP系统出库台账通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonObject).setMessage("CEMOP系统出库台账通知101库存成功！");
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    @Transactional
    @Override
    public ResponseMsg<Object> sendInitiateCoordinationData(CemopInitiateCoordinationDTO cemopInitiateCoordinationDTO) {
        log.info("101库存发起协调通知CEMOP系统数据" + cemopInitiateCoordinationDTO);
        CemopUploadDTO cemopUploadDTO = new CemopUploadDTO();
        cemopUploadDTO.setCemopInitiateCoordinationDTO(cemopInitiateCoordinationDTO);
        jsonToObject = cemopUtil.uploadUtil(cemopUploadDTO, CemopEnum.INITIATE_COORDINATION.getCode());
        log.info("101库存发起协调通知CEMOP系统成功" + cemopInitiateCoordinationDTO);
        return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("101库存发起协调通知CEMOP系统成功！");
    }

    @Transactional
    @Override
    public ResponseMsg<Object> getZeroApplicationData(JSONObject jsonObject) {
        log.info("CEMOP系统协调归零申请通知101库存数据" + jsonObject);
        jsonObject.put("description","CEMOP系统协调归零申请");
        try {
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.ZERO_APPLICATION.getCode());
            List<CemopZeroApplicationDTO> cemopZeroApplicationDTOS = cemopDownDTO.getCemopZeroApplicationDTOS();
            log.info("处理完成后的数据" + cemopZeroApplicationDTOS);
            for (CemopZeroApplicationDTO cemopZeroApplicationDTO : cemopZeroApplicationDTOS) {
                HashMap map = new HashMap();
                map.put("wmsDeliveryCoordinateId", cemopZeroApplicationDTO.getMomWmsDeliveryCoordinateId());
                map.put("userId", cemopZeroApplicationDTO.getUserId());
                map.put("endApplyDate", new Date());
                map.put("lastUpdateBy", cemopZeroApplicationDTO.getUserId());
                map.put("lastUpdateDate", new Date());
                map.put("ip", cemopZeroApplicationDTO.getIp());
                //协调单归零
                cemopMapper.updateCemopWmsDeliveryCo(map);
//                //协调单归零后通知Cemop
//                CemopZeroCoordinationDTO cemopZeroCoordinationDTO = new CemopZeroCoordinationDTO();
//                cemopZeroCoordinationDTO.setMomWmsDeliveryCoordinateId(cemopZeroApplicationDTO.getMomWmsDeliveryCoordinateId());
//                cemopZeroCoordinationDTO.setUserId(cemopZeroApplicationDTO.getUserId());
//                sendZeroCoordinationData(cemopZeroCoordinationDTO);
            }
            log.info("CEMOP系统协调归零申请通知101库存成功" + jsonObject);
            jsonObject.put("msg","CEMOP系统协调归零申请通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(cemopZeroApplicationDTOS).setMessage("CEMOP系统协调归零申请通知101库存成功！");
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    @Transactional
    @Override
    public ResponseMsg<Object> sendZeroCoordinationData(CemopZeroCoordinationDTO cemopZeroCoordinationDTO) {
        log.info("101库存协调归零通知CEMOP系统数据" + cemopZeroCoordinationDTO);
        CemopUploadDTO cemopUploadDTO = new CemopUploadDTO();
        cemopUploadDTO.setCemopZeroCoordinationDTO(cemopZeroCoordinationDTO);
        jsonToObject = cemopUtil.uploadUtil(cemopUploadDTO, CemopEnum.ZERO_COORDINATION.getCode());
        log.info("101库存协调归零通知CEMOP系统成功" + jsonToObject);
        return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("101库存协调归零通知CEMOP系统成功！");
    }

    @Transactional
    @Override
    public ResponseMsg<Object> getScanTransfer(JSONObject jsonObject) {
        log.info("CEMOP系统扫码移交至101库存数据" + jsonObject);
        jsonObject.put("description","CEMOP系统扫码移交");
        try {
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.SCAN_TRANSFER.getCode());
            List<CemopScanTransferDTO> cemopScanTransferDTOS = cemopDownDTO.getCemopScanTransferDTOS();
            log.info("处理完成后的数据" + cemopScanTransferDTOS);
            for (CemopScanTransferDTO cemopScanTransferDTO : cemopScanTransferDTOS) {
                WmsDeliveryPlan wmsDeliveryPlan = new WmsDeliveryPlan();
                wmsDeliveryPlan.setWmsDeliveryPlanId(cemopScanTransferDTO.getWmsDeliveryPlanId());
                wmsDeliveryPlan.setDeliveryDate(cemopScanTransferDTO.getSendDate());
                wmsDeliveryPlan.setDeliveryEmpCode(cemopScanTransferDTO.getSendUser());
                wmsDeliveryPlan.setDeliveryStatus(DeliveryStatusEnum.TRANSFERRED.getCode());
                wmsDeliveryPlan.setDeliveryQty(new BigDecimal(cemopScanTransferDTO.getRequireQty()));
                wmsDeliveryPlanService.updateById(wmsDeliveryPlan);
            }
            log.info("CEMOP系统扫码移交至101库存失败" + jsonObject);
            jsonObject.put("msg","CEMOP系统扫码移交至101库存失败");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(cemopScanTransferDTOS).setMessage("CEMOP系统扫码移交至101库存失败！");
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * 101库存AO配套台账通知CEMOP系统
     *
     * @param cemopSupportingLedgerDTO
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> sendAoSupportingLedger(CemopSupportingLedgerDTO cemopSupportingLedgerDTO) {
        log.info("101库存AO配套台账通知CEMOP系统数据" + cemopSupportingLedgerDTO);
        CemopUploadDTO cemopUploadDTO = new CemopUploadDTO();
        cemopUploadDTO.setCemopSupportingLedgerDTO(cemopSupportingLedgerDTO);
        jsonToObject = cemopUtil.uploadUtil(cemopUploadDTO, CemopEnum.AO_SUPPORTING_LEDGER.getCode());
        log.info("101库存AO配套台账通知CEMOP系统成功" + cemopSupportingLedgerDTO);
        return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("101库存AO配套台账通知CEMOP系统成功！");
    }

    /**
     * 101库存AO取消配套台账通知CEMOP系统
     *
     * @param cemopCancelSupportingLedgerDTO
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> sendCancelAoSupportingLedger(CemopCancelSupportingLedgerDTO cemopCancelSupportingLedgerDTO) {
        log.info("101库存AO取消配套台账通知CEMOP系统数据" + cemopCancelSupportingLedgerDTO);
        CemopUploadDTO cemopUploadDTO = new CemopUploadDTO();
        cemopUploadDTO.setCemopCancelSupportingLedgerDTO(cemopCancelSupportingLedgerDTO);
        jsonToObject = cemopUtil.uploadUtil(cemopUploadDTO, CemopEnum.CANCEL_AO_SUPPORTING_LEDGER.getCode());
        log.info("101库存AO配套台账通知CEMOP系统成功" + jsonToObject);
        return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("101库存AO配套台账通知CEMOP系统成功！");
    }

    /**
     * 101库存AO配套出库通知CEMOP系统
     *
     * @param cemopAoMatchingOutboundDTO
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> sendAoMatchingOutbound(CemopAoMatchingOutboundDTO cemopAoMatchingOutboundDTO) {
        log.info("101库存AO配套出库通知CEMOP系统数据" + cemopAoMatchingOutboundDTO);
        CemopUploadDTO cemopUploadDTO = new CemopUploadDTO();
        cemopUploadDTO.setCemopAoMatchingOutboundDTO(cemopAoMatchingOutboundDTO);
        jsonToObject = cemopUtil.uploadUtil(cemopUploadDTO, CemopEnum.AO_MATCHING_OUTBOUND.getCode());
        log.info("101库存AO配套出库通知CEMOP系统成功" + jsonToObject);
        return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("101库存AO配套出库通知CEMOP系统成功！");

    }

    @Transactional
    @Override
    public ResponseMsg<Object> sendAoRevokesOutbound(CemopAoRevokesOutboundDTO cemopAoRevokesOutboundDTO) {
        log.info("101库存AO撤销出库通知CEMOP系统数据" + cemopAoRevokesOutboundDTO);
        CemopUploadDTO cemopUploadDTO = new CemopUploadDTO();
        cemopUploadDTO.setCemopAoRevokesOutboundDTO(cemopAoRevokesOutboundDTO);
        jsonToObject = cemopUtil.uploadUtil(cemopUploadDTO, CemopEnum.AO_REVOKES_OUTBOUND.getCode());
        log.info("101库存AO撤销出库通知CEMOP系统成功" + jsonToObject);
        return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("101库存AO撤销出库通知CEMOP系统成功！");
    }

    /**
     * 101库存AO配套移交接收通知CEMOP系统
     *
     * @param cemopAoSupportingTransferDTO
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> sendAoSupportingTransfer(CemopAoSupportingTransferDTO cemopAoSupportingTransferDTO) {
        log.info("101库存AO配套移交接收通知CEMOP系统数据" + cemopAoSupportingTransferDTO);
        CemopUploadDTO cemopUploadDTO = new CemopUploadDTO();
        cemopUploadDTO.setCemopAoSupportingTransferDTO(cemopAoSupportingTransferDTO);
        jsonToObject = cemopUtil.uploadUtil(cemopUploadDTO, CemopEnum.AO_SUPPORTING_TRANSFER.getCode());
        log.info("101库存AO配套移交通知CEMOP系统成功" + jsonToObject);
        return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("101库存AO配套移交通知CEMOP系统成功！");
    }

    /**
     * CEMOP系统分配台账信息通知101库存
     *
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> getAllocateLedgerInformation(JSONObject jsonObject) {
        log.info("CEMOP系统分配台账信息通知101库存数据" + jsonObject);
        jsonObject.put("description","CEMOP系统分配台账信息");
        try{
            CemopDownDTO cemopDownDTO = new CemopDownDTO();
            cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.ALLOCATE_LEDGER_INFORMATION.getCode());
            List<CemopAllocateLedgerInformationDTO> cemopAllocateLedgerInformationDTOS = cemopDownDTO.getCemopAllocateLedgerInformationDTOS();
            log.info("处理完成后的数据" + cemopAllocateLedgerInformationDTOS);
            for (CemopAllocateLedgerInformationDTO cemopAllocateLedgerInformationDTO : cemopAllocateLedgerInformationDTOS) {
                //查询台账表并更新占用数量
                LambdaQueryWrapper<WmsItemInventory> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(WmsItemInventory::getWmsItemInventoryId, cemopAllocateLedgerInformationDTO.getMomWmsItemInventoryId());
                WmsItemInventory wmsItemInventory = wmsItemInventoryService.getOne(queryWrapper1);
                if (wmsItemInventory != null) {
                    BigDecimal engagedQty = wmsItemInventory.getEngagedQty();
                    engagedQty = engagedQty != null ? engagedQty : BigDecimal.ZERO;
                    wmsItemInventory.setEngagedQty(engagedQty.add(new BigDecimal(cemopAllocateLedgerInformationDTO.getDstrQty())));
                    log.info("处理完成后的台账信息" + wmsItemInventory);
                    wmsItemInventoryService.updateById(wmsItemInventory);
                } else {
                    log.info("CEMOP系统分配台账信息通知101库存失败!台账信息不存在" + jsonObject);
                    jsonToObject = convertToJSONArray(cemopDownDTO, jsonObject);
                    return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("CEMOP系统分配台账信息通知101库存成功！");
                }
                String Hid = UUID.randomUUID().toString().replace("-", "");
                // 插入占用信息表
                String momWmsInvOutAllotmentId = cemopAllocateLedgerInformationDTO.getMomWmsInvOutAllotmentId();
                WmsInvOutAllotment wmsInvOutAllotment1 = new WmsInvOutAllotment();
                wmsInvOutAllotment1.setWmsInvOutAllotmentId(momWmsInvOutAllotmentId);
                wmsInvOutAllotment1.setAllotmentQty(new BigDecimal(cemopAllocateLedgerInformationDTO.getDstrQty()));
                wmsInvOutAllotment1.setAllotmentStatus("0");
                wmsInvOutAllotment1.setCreatedBy(cemopAllocateLedgerInformationDTO.getUserId());
                wmsInvOutAllotment1.setWmsItemInventoryId(cemopAllocateLedgerInformationDTO.getMomWmsItemInventoryId());
                wmsInvOutAllotment1.setWmsInvOutBillHId(Hid);
                log.info("处理完成后的占用表信息" + wmsInvOutAllotment1);
                iWmsInvOutAllotmentService.save(wmsInvOutAllotment1);
                //插入出库占用主表
                LambdaQueryWrapper<WmsInvOutBillH> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmsInvOutBillH::getWmsInvOutBillHId, cemopAllocateLedgerInformationDTO.getMomWmsInvOutAllotmentId());
                WmsInvOutBillH one = iWmsInvOutBillHService.getOne(queryWrapper);
                WmsInvOutBillH wmsInvOutBillH = new WmsInvOutBillH();
                if (one == null) {
                    wmsInvOutBillH.setWmsInvOutBillHId(Hid);
                    wmsInvOutBillH.setProductCode(wmsItemInventory.getProductCode());
                    wmsInvOutBillH.setBatchNo(wmsItemInventory.getBatchNo());
                    wmsInvOutBillH.setTaskNo(wmsItemInventory.getTaskNo());
                    wmsInvOutBillH.setStartLotNo(wmsItemInventory.getStartLotNo());
                    wmsInvOutBillH.setEndLotNo(wmsItemInventory.getEndLotNo());
//                    wmsInvOutBillH.setAoNo(wmsItemInventory.getA());
                    log.info("处理完成后的出库主表信息" + wmsInvOutAllotment1);
                    iWmsInvOutBillHService.save(wmsInvOutBillH);
                }

                //插入出库占用子表
                WmsInvOutBillL wmsInvOutBillL = new WmsInvOutBillL();
                wmsInvOutBillL.setWmsInvOutBillLId(UUID.randomUUID().toString().replace("-", ""));
                wmsInvOutBillL.setWmsInvOutBillHId(wmsInvOutBillH.getWmsInvOutBillHId());
                wmsInvOutBillL.setApplyQty(new BigDecimal(cemopAllocateLedgerInformationDTO.getDstrQty()));
                wmsInvOutBillL.setAttribute18(wmsItemInventory.getWmsItemInventoryId());
                wmsInvOutBillL.setAttribute17(wmsItemInventory.getWmsDeliveryPlanId());
                wmsInvOutBillL.setAttribute16(momWmsInvOutAllotmentId);
                log.info("处理完成后的出库子表信息" + wmsInvOutBillL);
                iWmsInvOutBillLService.save(wmsInvOutBillL);
            }
            jsonToObject = convertToJSONArray(cemopDownDTO, jsonObject);
            log.info("CEMOP系统分配台账信息通知101库存成功" + jsonObject);
            jsonObject.put("msg","CEMOP系统分配台账信息通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("CEMOP系统分配台账信息通知101库存成功！");
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * CEMOP系统台账出库通知101库存
     *
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> getLedgerOutbound(JSONObject jsonObject) {
        log.info("CEMOP系统台账出库通知101库存数据" + jsonObject);
        jsonObject.put("description","CEMOP系统台账出库");
        try {
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.LEDGER_OUTBOUND.getCode());
            List<CemopLedgerOutboundDTO> cemopLedgerOutboundDTOS = cemopDownDTO.getCemopLedgerOutboundDTOS();
            log.info("处理完成后的数据" + cemopLedgerOutboundDTOS);
            for (CemopLedgerOutboundDTO cemopLedgerOutboundDTO : cemopLedgerOutboundDTOS) {
                String momWmsInvOutAllotmentId = cemopLedgerOutboundDTO.getMomWmsInvOutAllotmentId();
                //查看占用表是否存在
                LambdaQueryWrapper<WmsInvOutAllotment> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmsInvOutAllotment::getWmsInvOutAllotmentId, momWmsInvOutAllotmentId);
                queryWrapper.eq(WmsInvOutAllotment::getAllotmentStatus, "0");
                WmsInvOutAllotment wmsInvOutAllotment = iWmsInvOutAllotmentService.getOne(queryWrapper);
                log.info("占用表信息" + wmsInvOutAllotment);
                if (wmsInvOutAllotment == null) {
                    log.info("CEMOP系统台账出库通知101库存失败!占用表信息不存在" + jsonObject);
                    throw new RuntimeException("CEMOP系统台账出库通知101库存失败!占用表信息不存在");
                }
                //查看出库流水是否存在
                LambdaQueryWrapper<WmsItemTransaction> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(WmsItemTransaction::getAttribute20, momWmsInvOutAllotmentId);
                wrapper1.eq(WmsItemTransaction::getInvTransactStatus, "0");
                WmsItemTransaction wmsItemTransaction = iWmsItemTransactionService.getOne(wrapper1);
                log.info("出库流水信息" + wmsItemTransaction);
                if (wmsItemTransaction != null) {
                    log.info("CEMOP系统台账出库通知101库存失败!出库流水已经存在,请勿重复出库" + jsonObject);
                    throw new RuntimeException("CEMOP系统台账出库通知101库存失败!出库流水已经存在,请勿重复出库");
                }
                //获取台账信息
                String wmsItemInventoryId = wmsInvOutAllotment.getWmsItemInventoryId();
                LambdaQueryWrapper<WmsItemInventory> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(WmsItemInventory::getWmsItemInventoryId, wmsItemInventoryId);
                WmsItemInventory wmsItemInventory = wmsItemInventoryService.getOne(queryWrapper1);
                log.info("台账信息" + wmsItemInventory);
                if (wmsItemInventory == null) {
                    log.info("CEMOP系统台账出库通知101库存失败!台账信息不存在" + jsonObject);
                    throw new RuntimeException("CEMOP系统台账出库通知101库存失败!台账信息不存在");
                }
                BigDecimal engagedQty = wmsItemInventory.getEngagedQty();
                engagedQty = engagedQty != null ? engagedQty : BigDecimal.ZERO;
                wmsItemInventory.setEngagedQty(engagedQty.subtract(wmsInvOutAllotment.getAllotmentQty()));
                log.info("修改后的台账数据" + wmsItemInventory);
                wmsItemInventoryService.updateById(wmsItemInventory);
                HashMap<Object, Object> map = new HashMap<>();
                map.put("wmsItemInventoryId", wmsItemInventory.getWmsItemInventoryId());
                map.put("allotmentQty", wmsInvOutAllotment.getAllotmentQty());
    //            map.put("wmsItemTransactionId", wmsItemTransaction.getWmsItemTransactionId());
                wmsInvOutBillService.erpOutOccupyTransaction(map);
            }
            jsonToObject = convertToJSONArray(cemopDownDTO, jsonObject);
            log.info("CEMOP系统台账出库通知101库存成功" + jsonObject);
            jsonObject.put("msg","CEMOP系统台账出库通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("CEMOP系统分配台账信息通知101库存成功！");
        } catch (RuntimeException e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * CEMOP系统取消台账分配通知101库存
     *
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> getCancelLedgerAllocation(JSONObject jsonObject) {
        log.info("CEMOP系统取消台账分配通知101库存数据" + jsonObject);
        jsonObject.put("description","CEMOP系统取消台账分配");
        try {
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.CANCEL_LEDGER_ALLOCATION.getCode());
            List<CemopCancelLedgerAllocationDTO> cemopCancelLedgerAllocationDTOS = cemopDownDTO.getCemopCancelLedgerAllocationDTOS();
            log.info("处理完成后的数据" + cemopCancelLedgerAllocationDTOS);
            for (CemopCancelLedgerAllocationDTO cemopCancelLedgerAllocationDTO : cemopCancelLedgerAllocationDTOS) {
                String momWmsInvOutAllotmentId = cemopCancelLedgerAllocationDTO.getMomWmsInvOutAllotmentId();
                //查询台账事务流水
                LambdaQueryWrapper<WmsItemTransaction> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(WmsItemTransaction::getAttribute20, momWmsInvOutAllotmentId);
                wrapper.eq(WmsItemTransaction::getInvTransactStatus, "0");
                WmsItemTransaction one = iWmsItemTransactionService.getOne(wrapper);
                log.info("台账事务流水信息" + one);
                WmsInvOutAllotment wmsInvOutAllotment = null;
                WmsItemTransaction wmsItemTransaction = null;
                if (one == null) {
                    //查看占用表是否存在
                    LambdaQueryWrapper<WmsInvOutAllotment> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WmsInvOutAllotment::getWmsInvOutAllotmentId, momWmsInvOutAllotmentId);
                    queryWrapper.ne(WmsInvOutAllotment::getAllotmentStatus, "0");
                    wmsInvOutAllotment = iWmsInvOutAllotmentService.getOne(queryWrapper);
                    log.info("占用表信息" + wmsInvOutAllotment);
                    if (wmsInvOutAllotment == null) {
                        log.info("CEMOP系统取消台账分配通知101库存失败!无出库占用信息,请重新下发出库占用" + jsonObject);
                        throw new RuntimeException("CEMOP系统取消台账分配通知101库存失败!无出库占用信息,请重新下发出库占用");
                    }
                } else {
                    LambdaQueryWrapper<WmsItemTransaction> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(WmsItemTransaction::getAttribute20, momWmsInvOutAllotmentId);
                    wrapper1.eq(WmsItemTransaction::getInvTransactStatus, "4");
                    wmsItemTransaction = iWmsItemTransactionService.getOne(wrapper1);
                    log.info("库存流水信息" + wmsItemTransaction);
                    if (wmsItemTransaction == null) {
                        log.info("CEMOP系统取消台账分配通知101库存失败!无出库撤销信息,请重新下发出库撤销" + jsonObject);
                        throw new RuntimeException("CEMOP系统取消台账分配通知101库存失败!无出库撤销信息,请重新下发出库撤销");
                    }
                }
                //获取占用数量
                BigDecimal allotmentQty = wmsInvOutAllotment.getAllotmentQty();
                //获取台账信息
                String wmsItemInventoryId = wmsInvOutAllotment.getWmsItemInventoryId();
                WmsItemInventory wmsItemInventory = wmsItemInventoryService.getById(wmsItemInventoryId);
                //减掉占用数量
                BigDecimal engagedQty = wmsItemInventory.getEngagedQty();
                engagedQty = engagedQty != null ? engagedQty : BigDecimal.ZERO;
                wmsItemInventory.setEngagedQty(engagedQty.subtract(allotmentQty));
                log.info("修改后的台账数据" + wmsItemInventory);
                wmsItemInventoryService.updateById(wmsItemInventory);
                //删除出库主表、子表
                LambdaQueryWrapper<WmsInvOutBillH> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmsInvOutBillH::getWmsInvOutBillHId, wmsInvOutAllotment.getWmsInvOutBillHId());
                boolean remove = iWmsInvOutBillHService.remove(queryWrapper);
                log.info("删除出库主表是否删掉" + remove);
                LambdaQueryWrapper<WmsInvOutBillL> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(WmsInvOutBillL::getWmsInvOutBillHId, wmsInvOutAllotment.getWmsInvOutBillHId());
                boolean remove1 = iWmsInvOutBillLService.remove(queryWrapper1);
                log.info("删除出库子表是否删掉" + remove1);
            }
            log.info("CEMOP系统取消台账分配通知101库存成功" + jsonObject);
            jsonToObject = convertToJSONArray(cemopDownDTO, jsonObject);
            jsonObject.put("msg","CEMOP系统取消台账分配通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("CEMOP系统取消台账分配通知101库存成功！");
        } catch (RuntimeException e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * CEMOP系统取消台账出库通知101库存
     *
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> getCancelLedgerOutbound(JSONObject jsonObject) {
        log.info("CEMOP系统取消台账出库通知101库存数据" + jsonObject);
        jsonObject.put("description","CEMOP系统取消台账出库");
        try {
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.CANCEL_LEDGER_OUTBOUND.getCode());
            List<CemopCancelLedgerOutboundDTO> cemopCancelLedgerOutboundDTOS = cemopDownDTO.getCemopCancelLedgerOutboundDTOS();
            log.info("处理完成后的数据" + cemopCancelLedgerOutboundDTOS);
            for (CemopCancelLedgerOutboundDTO cemopCancelLedgerOutboundDTO : cemopCancelLedgerOutboundDTOS) {
                LambdaQueryWrapper<WmsItemTransaction> wrapper1 = new LambdaQueryWrapper<>();
                String momWmsInvOutAllotmentId = cemopCancelLedgerOutboundDTO.getMomWmsInvOutAllotmentId();
                wrapper1.eq(WmsItemTransaction::getAttribute20, momWmsInvOutAllotmentId);
                wrapper1.eq(WmsItemTransaction::getInvTransactStatus, "0");
                WmsItemTransaction wmsItemTransaction = iWmsItemTransactionService.getOne(wrapper1);
                if (wmsItemTransaction == null) {
                    log.info("CEMOP系统台账出库通知101库存失败!无出库信息,请重新下发出库" + jsonObject);
                    throw new RuntimeException("CEMOP系统台账出库通知101库存失败!无出库信息,请重新下发出库");
                }
                HashMap<Object, Object> map = new HashMap<>();
                map.put("wmsInvOutAllotmentId", momWmsInvOutAllotmentId);
                wmsInvOutBillService.erpOutOccupyCancel(map);
            }
            log.info("CEMOP系统取消台账出库通知101库存成功" + jsonObject);
            jsonToObject = convertToJSONArray(cemopDownDTO, jsonObject);
            jsonObject.put("msg","CEMOP系统取消台账出库通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("CEMOP系统取消台账出库通知101库存成功！");
        } catch (RuntimeException e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }

    }

    /**
     * CEMOP系统接收拆分的合格证通知101库存
     *
     * @param jsonObject
     * @return
     */
    @Override
    public ResponseMsg<Object> newCefcdEcd(JSONObject jsonObject) {
        log.info("CEMOP系统接收拆分的合格证通知101库存" + jsonObject);
        jsonObject.put("description","CEMOP系统接收拆分的合格证");
        try {
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.CANCEL_LEDGER_OUTBOUND.getCode());
            List<NewCefcdecdDTO> newCefcdecdDTOS = cemopDownDTO.getNewCefcdecdDTOS();
            for (NewCefcdecdDTO newCefcdecdDTO : newCefcdecdDTOS) {
                LambdaUpdateWrapper<WmsDeliveryPlan> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(WmsDeliveryPlan::getMesCheckQualiticationId, newCefcdecdDTO.getCefcdEcd());
                updateWrapper.set(WmsDeliveryPlan::getAttribute14Desc, newCefcdecdDTO.getFoudrNo());
                updateWrapper.eq(WmsDeliveryPlan::getWmsDeliveryPlanId, newCefcdecdDTO.getMomWmsDeliveryPlanId());
                log.info("更新交接单数据" + updateWrapper);
                wmsDeliveryPlanService.update(updateWrapper);
            }
            jsonObject.put("msg","CEMOP系统接收拆分的合格证通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return null;
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * CEMOP与SERP系统删除交接单通知101库存
     *
     * @param jsonObject
     * @return
     */
    @Override
    public ResponseMsg<Object> getCancelDeliver(JSONObject jsonObject) {
        log.info("CEMOP与SERP系统删除交接单通知101库存" + jsonObject);
        jsonObject.put("description","CEMOP与SERP系统删除交接单");
        try {
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.CANCEL_DELIVER.getCode());
            List<CemopCancelDeliverDTO> cancelDeliverDTOS = cemopDownDTO.getCemopCancelDeliverDTOS();
            for (CemopCancelDeliverDTO cancelDeliverDTO : cancelDeliverDTOS) {
                LambdaUpdateWrapper<WmsDeliveryPlan> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(WmsDeliveryPlan::getLastUpdatedBy, cancelDeliverDTO.getUserId());
                updateWrapper.set(WmsDeliveryPlan::getLastUpdateDate, new Date());
                updateWrapper.set(WmsDeliveryPlan::getDeliveryStatus, '5');
                updateWrapper.eq(WmsDeliveryPlan::getWmsDeliveryPlanId, cancelDeliverDTO.getMomWmsDeliveryPlanId());
                wmsDeliveryPlanService.update(updateWrapper);
            }
            jsonObject.put("msg","CEMOP与SERP系统删除交接单通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return null;
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }


    /**
     * 装配系统工人驳回物料至101库存
     *
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> getReject(JSONObject jsonObject) throws FileNotFoundException {
        log.info("CEMOP系统工人驳回物料至101库存数据" + jsonObject);
        jsonObject.put("description","装配系统工人驳回物料");
        //解压文件
        String fileUrl = jsonObject.get("fileUrl").toString();
        try {
            List<File> files = cemopXmlUtil.downloadAndExtractXMLFiles(fileUrl);
            //解析xml文件，拿到月计划内容（工作包、AO、物料）
            FileInputStream fileInputStream = new FileInputStream(files.get(0));
            XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
            RootDTO rootDTO = new RootDTO();
            List<Map<String, String>> list1 = xmlReadUtil.getAttributesByTagName("MOM_ASS_MATERIAL_RECEIVE");
            List<CemopRejectDTO> cemopRejectDTOS = new ArrayList<>();
            for (Map<String, String> map : list1) {
                CemopRejectDTO cemopRejectDTO = new CemopRejectDTO();
                xmlReadUtil.mapToDTO(map, cemopRejectDTO);
                cemopRejectDTOS.add(cemopRejectDTO);
            }
            log.info("解析完成后的数据" + cemopRejectDTOS);
            for (CemopRejectDTO cemopRejectDTO : cemopRejectDTOS) {

                WmsDeliveryPlan wmsDeliveryPlan = wmsDeliveryPlanService.getById(cemopRejectDTO.getMOM_DELIVERY_PLAN_ID());
                wmsDeliveryPlan.setWmsDeliveryPlanId(cemopRejectDTO.getMOM_DELIVERY_PLAN_ID());
                wmsDeliveryPlan.setRejectDate(cemopRejectDTO.getRETUEN_DATE());
                wmsDeliveryPlan.setRejectEmpCode(cemopRejectDTO.getRETUEN_USER());
                wmsDeliveryPlan.setDeliveryStatus(DeliveryStatusEnum.TRANSFERRED.getCode());
                wmsDeliveryPlan.setMesUseQty(new BigDecimal(cemopRejectDTO.getRETUEN_QTY()));
                wmsDeliveryPlan.setRejectReason(cemopRejectDTO.getRETUEN_DESC());
                log.info("交接单数据" + wmsDeliveryPlan);
                wmsDeliveryPlanService.updateById(wmsDeliveryPlan);

                LambdaUpdateWrapper<WmsDeliveryPlan> updateWrapper = new LambdaUpdateWrapper();
                updateWrapper.set(WmsDeliveryPlan::getRejectEmpCode, cemopRejectDTO.getRETUEN_USER());
                updateWrapper.set(WmsDeliveryPlan::getRejectDate, cemopRejectDTO.getRETUEN_DATE());
                updateWrapper.set(WmsDeliveryPlan::getRejectReason, cemopRejectDTO.getRETUEN_DESC());
                updateWrapper.set(WmsDeliveryPlan::getMesUseQty, cemopRejectDTO.getRETUEN_QTY());
                updateWrapper.set(WmsDeliveryPlan::getDeliveryStatus, "4");
                updateWrapper.eq(WmsDeliveryPlan::getWmsDeliveryPlanId, cemopRejectDTO.getMOM_DELIVERY_PLAN_ID());
                log.info("更新交接单数据" + updateWrapper);
                wmsDeliveryPlanService.update(updateWrapper);


                LambdaUpdateWrapper<MsAoMatchInfo> updMatchInfo = new LambdaUpdateWrapper<>();
                updMatchInfo.set(MsAoMatchInfo::getLastUpdateDate, cemopRejectDTO.getRETUEN_DATE());
                updMatchInfo.set(MsAoMatchInfo::getRejectQty, cemopRejectDTO.getRETUEN_QTY());
                updMatchInfo.set(MsAoMatchInfo::getDeliveryState, "06");
                WmsDeliveryPlan byId = wmsDeliveryPlanService.getById(cemopRejectDTO.getMOM_DELIVERY_PLAN_ID());
                updMatchInfo.eq(MsAoMatchInfo::getMsAoMatchInfoId, byId.getAttribute1());
                log.info("更新matchinfo表数据" + updMatchInfo);
                iMsAoMatchInfoNewService.update(updMatchInfo);


                LambdaQueryWrapper<WmsInvOutAllotment> outAllotment = new LambdaQueryWrapper<>();
                outAllotment.eq(WmsInvOutAllotment::getWmsItemInventoryId, wmsDeliveryPlan.getWmsItemInventoryId());
                WmsInvOutAllotment wmsInvOutAllotment = iWmsInvOutAllotmentService.getOne(outAllotment);
                log.info("占用表数据" + wmsInvOutAllotment);

                CemopCancelSupportingLedgerDTO cemopCancelSupportingLedgerDTO = new CemopCancelSupportingLedgerDTO();
                cemopCancelSupportingLedgerDTO.setMomWmsInvOutAllotmentId(wmsInvOutAllotment.getWmsInvOutAllotmentId());
                cemopCancelSupportingLedgerDTO.setUserId(cemopRejectDTO.getRETUEN_USER());
                sendCancelAoSupportingLedger(cemopCancelSupportingLedgerDTO);
            }
            log.info("CEMOP系统工人驳回物料至101成功" + jsonObject);
            jsonObject.put("msg","CEMOP系统工人驳回物料至101成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(cemopRejectDTOS).setMessage("CEMOP系统工人驳回物料至101成功！");
        } catch (FileNotFoundException e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * 装配系统工人接收物料至101库存
     *
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> receivingMaterial(JSONObject jsonObject) throws FileNotFoundException {
        log.info("CEMOP系统工人接收物料至101库存数据" + jsonObject);
        jsonObject.put("description","装配系统工人接收物料");
        try {
            //解压文件
            String fileUrl = jsonObject.get("fileUrl").toString();
            List<File> files = cemopXmlUtil.downloadAndExtractXMLFiles(fileUrl);
            //解析xml文件，拿到月计划内容（工作包、AO、物料）
            FileInputStream fileInputStream = new FileInputStream(files.get(0));
            XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
            RootDTO rootDTO = new RootDTO();
            List<Map<String, String>> list1 = xmlReadUtil.getAttributesByTagName("MOM_ASS_MATERIAL_RECEIVE");
            List<CemopReceiveDTO> cemopReceiveDTOS = new ArrayList<>();
            for (Map<String, String> map : list1) {
                CemopReceiveDTO cemopRejectDTO = new CemopReceiveDTO();
                xmlReadUtil.mapToDTO(map, cemopRejectDTO);
                cemopReceiveDTOS.add(cemopRejectDTO);
            }
            log.info("解析完成后的数据" + cemopReceiveDTOS);
            for (CemopReceiveDTO cemopReceiveDTO : cemopReceiveDTOS) {
                LambdaUpdateWrapper<WmsDeliveryPlan> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(WmsDeliveryPlan::getReceiveEmpCode, cemopReceiveDTO.getRECEIVE_USER());
                updateWrapper.set(WmsDeliveryPlan::getReceiveDate, cemopReceiveDTO.getRECEIVE_DATE());
                updateWrapper.set(WmsDeliveryPlan::getReceiveQty, cemopReceiveDTO.getRECEIVE_QTY());
                updateWrapper.set(WmsDeliveryPlan::getDeliveryStatus, "3");
                updateWrapper.eq(WmsDeliveryPlan::getWmsDeliveryPlanId, cemopReceiveDTO.getMOM_DELIVERY_PLAN_ID());
                log.info("更新交接单数据" + updateWrapper);
                wmsDeliveryPlanService.update(updateWrapper);
                LambdaUpdateWrapper<MsAoMatchInfo> updMatchInfo = new LambdaUpdateWrapper<>();
                updMatchInfo.set(MsAoMatchInfo::getLastUpdateDate, cemopReceiveDTO.getRECEIVE_DATE());
                updMatchInfo.set(MsAoMatchInfo::getDepartReceiveTime, cemopReceiveDTO.getRECEIVE_DATE());
                updMatchInfo.set(MsAoMatchInfo::getDeliveryEmpCode, cemopReceiveDTO.getRECEIVE_USER());
                updMatchInfo.set(MsAoMatchInfo::getReceiveQty, new BigDecimal(cemopReceiveDTO.getRECEIVE_QTY()));
                updMatchInfo.set(MsAoMatchInfo::getDeliveryState, "06");
                WmsDeliveryPlan byId = wmsDeliveryPlanService.getById(cemopReceiveDTO.getMOM_DELIVERY_PLAN_ID());
                updMatchInfo.eq(MsAoMatchInfo::getMsAoMatchInfoId, byId.getAttribute1());
                log.info("更新matchinfo表数据" + updMatchInfo);
                iMsAoMatchInfoNewService.update(updMatchInfo);
                HashMap map = new HashMap();
                map.put("WMS_DELIVERY_PLAN_ID", cemopReceiveDTO.getMOM_DELIVERY_PLAN_ID());
                int cnt = wmsDeliverPlanDao.queryIsExistsOutTransaction(map);
                if (cnt == 0) {
                    String wmsInvOutAllotmentId = wmsDeliverPlanDao.queryWmsInvOutAllotmentId(map);
                    if (wmsInvOutAllotmentId != null && "".equals(wmsInvOutAllotmentId)) {
                        map.put("WMS_INV_OUT_ALLOTMENT_ID", wmsInvOutAllotmentId);
                        wmsDeliverPlanService.MakeMaterialCheck(map);
                    }
                }
                //101库存AO配套移交通知CEMOP系统
                CemopAoSupportingTransferDTO cemopAoSupportingTransferDTO = new CemopAoSupportingTransferDTO();
                cemopAoSupportingTransferDTO.setMomWmsDeliveryPlanId(cemopReceiveDTO.getMOM_DELIVERY_PLAN_ID());
                cemopAoSupportingTransferDTO.setUserId(cemopReceiveDTO.getRECEIVE_USER());
                this.sendAoSupportingTransfer(cemopAoSupportingTransferDTO);
            }
            log.info("CEMOP系统工人接收物料至101成功" + jsonObject);
            jsonObject.put("msg","CEMOP系统工人接收物料至101成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(cemopReceiveDTOS).setMessage("CEMOP系统工人接收物料至101成功！");
        } catch (FileNotFoundException e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * 101库存发送配套信息至装配
     *
     * @param
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> sendMatchBillInfo() {
        // 查询物料配套信息
        List<CemopMathchBillVO> cemopMathchBillVOS = cemopMapper.selectCemopMathchBillLInfo();
        log.info("查询物料配套信息数据" + cemopMathchBillVOS);
        if (cemopMathchBillVOS == null || cemopMathchBillVOS.isEmpty()) {
            log.warn("没有发现物料配套信息数据");
            return new ResponseMsg<>().setResponseBody(null).setMessage("物料配套信息无数据，请检查数据!").setRetCode("404");
        }
        CemopXmlDTO cemopXmlDTO = new CemopXmlDTO();
        cemopXmlDTO.setXmlType(CemopXmlEnum.SUPPORTING_INFORMATION.getCode());
        List<CemopXmlDTO> cemopXmlDTOList = new ArrayList<>();
        for (CemopMathchBillVO cemopMathchBillVO : cemopMathchBillVOS) {
            if (cemopMathchBillVO == null) {
                log.warn("物料配套信息对象为空，跳过处理");
                continue;
            }
            HashMap map = new HashMap<>();
            if (("02").equals(cemopMathchBillVO.getMaterialStateValue())) {
                map.put("MATERIAL_STATE", "6");
            } else {
                map.put("MATERIAL_STATE", "0");
            }
            map.put("MOM_ASS_SETOUT_MATERIAL_ID", cemopMathchBillVO.getMomAssSetoutMaterialIdValue());
            //20250213新增配套数量
            map.put("MATCH_QTY", cemopMathchBillVO.getMatchQty());
            CemopXmlDTO tableDTO = cemopXmlUtil.createTableDTO(cemopMathchBillVO.getTableName(), map);
            cemopXmlDTOList.add(tableDTO);
        }
        cemopXmlDTO.setCemopXmlDTOList(cemopXmlDTOList);
        JSONObject xml = cemopXmlUtil.createXml(cemopXmlDTO);
        if (xml == null) {
            log.error("生成XML失败！");
            return new ResponseMsg<>().setResponseBody(null).setMessage("生成XML失败").setRetCode("500");
        }
        return new ResponseMsg<>().setResponseBody(xml).setMessage("101库存发送配套信息至装配成功！").setRetCode("200");
    }


    /**
     * 101库存发送分拣信息至装配
     *
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> sendMatchSortingInfo(String matchInfoId) {
        log.info("matchInfoId数据" + matchInfoId);
        // 查询物料配套信息
        List<CemopMathchSortingVO> cemopMathchBillVOS = cemopMapper.selectCemopMathchSortingInfo(matchInfoId);
        if (cemopMathchBillVOS == null || cemopMathchBillVOS.isEmpty()) {
            log.warn("没有发现物料分拣信息数据");
            return new ResponseMsg<>().setResponseBody(null).setMessage("物分拣信息无数据，请检查数据!").setRetCode("404");
        }
        CemopXmlDTO cemopXmlDTO = new CemopXmlDTO();
        cemopXmlDTO.setXmlType(CemopXmlEnum.DELIVERY.getCode());
        List<CemopXmlDTO> cemopXmlDTOList = new ArrayList<>();
        for (CemopMathchSortingVO cemopMathchSortingVO : cemopMathchBillVOS) {
            if (cemopMathchSortingVO == null) {
                log.warn("分拣信息对象为空，跳过处理");
                continue;
            }
            HashMap map = new HashMap<>();
            map.put("IS_SORT", cemopMathchSortingVO.getISSORT());
            map.put("MOM_ASS_SETOUT_MATERIAL_ID", cemopMathchSortingVO.getMOMASSSETOUTMATERIALID());
            //新增分拣数量
            map.put("SORT_QTY", cemopMathchSortingVO.getSortQty());
            CemopXmlDTO tableDTO = cemopXmlUtil.createTableDTO(cemopMathchSortingVO.getTableName(), map);
            cemopXmlDTOList.add(tableDTO);
        }
        cemopXmlDTO.setCemopXmlDTOList(cemopXmlDTOList);
        JSONObject xml = cemopXmlUtil.createXml(cemopXmlDTO);
        if (xml == null) {
            log.error("生成XML失败！");
            return new ResponseMsg<>().setResponseBody(null).setMessage("生成XML失败").setRetCode("500");
        }
        return new ResponseMsg<>().setResponseBody(xml).setMessage("101库存发送分拣信息至装配！").setRetCode("200");
    }

    /**
     * 101库存配套物料信息至装配
     *
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> sendMaterialInfo(List<String> plandIds) {
        log.info("plandIds数据" + plandIds);
        try {
            // 查询物料配套信息
            List<CemopMaterialInfoVO> cemopMaterialInfoVOS = cemopMapper.selectCemopMaterialInfo(plandIds);
            if (cemopMaterialInfoVOS == null || cemopMaterialInfoVOS.isEmpty()) {
                log.warn("没有发现配套物料信息信息数据");
                return new ResponseMsg<>().setResponseBody(null).setMessage("101库存配套物料信息至装配无数据，请检查数据!").setRetCode("404");
            }
            CemopXmlDTO cemopXmlDTO = new CemopXmlDTO();
            cemopXmlDTO.setXmlType(CemopXmlEnum.SUPPORTING_MATERIALS.getCode());
            List<CemopXmlDTO> cemopXmlDTOList = new ArrayList<>();
            for (CemopMaterialInfoVO cemopMaterialInfoVO : cemopMaterialInfoVOS) {
                if (cemopMaterialInfoVO == null) {
                    log.warn("分拣信息对象为空，跳过处理");
                    continue;
                }
                HashMap map = new HashMap<>();
                map.put("MODLS_ECD", cemopMaterialInfoVO.getModlsEcd() != null ? cemopMaterialInfoVO.getModlsEcd() : "");
                map.put("BCH_NO", cemopMaterialInfoVO.getBchNo() != null ? cemopMaterialInfoVO.getBchNo() : "");
                map.put("SORTIE_NO", cemopMaterialInfoVO.getSortieNo() != null ? cemopMaterialInfoVO.getSortieNo() : "");
                map.put("AO_NO", cemopMaterialInfoVO.getAoNo() != null ? cemopMaterialInfoVO.getAoNo() : "");
                map.put("MATING_STATE", cemopMaterialInfoVO.getMatingState() != null ? cemopMaterialInfoVO.getMatingState() : "");
                //新增两个字段mds_item_id  主数据物料ID 、process_status_no 工艺文件状态号
                map.put("MDS_ITEM_ID", cemopMaterialInfoVO.getMdsItemId() != null ? cemopMaterialInfoVO.getMdsItemId() : "");
                map.put("PROCESS_STATUS_NO", cemopMaterialInfoVO.getProcessStatusNo() != null ? cemopMaterialInfoVO.getProcessStatusNo() : "");
                //转换-20250117
                switch (cemopMaterialInfoVO.getMdsItemType()) {
                    case "M":
                        map.put("MDS_ITEM_TYPE", "零件");
                        break;
                    case "F":
                        map.put("MDS_ITEM_TYPE", "成品");
                        break;
                    case "Z":
                        map.put("MDS_ITEM_TYPE", "标准件");
                        break;
                    case "S":
                        map.put("MDS_ITEM_TYPE", "成品虚件");
                        break;
                    default:
                        // 可以添加默认处理逻辑
                        log.info("未找到匹配类型{}", cemopMaterialInfoVO.getMdsItemType());
                        break;
                }
                map.put("MDS_ITEM_CODE", cemopMaterialInfoVO.getMdsItemCode() != null ? cemopMaterialInfoVO.getMdsItemCode() : "");
                map.put("MDS_ITEM_NAME", cemopMaterialInfoVO.getMdsItemName() != null ? cemopMaterialInfoVO.getMdsItemName() : "");
                map.put("MARQUE", cemopMaterialInfoVO.getMarque() != null ? cemopMaterialInfoVO.getMarque() : "");
                map.put("SPECS", cemopMaterialInfoVO.getSpecs() != null ? cemopMaterialInfoVO.getSpecs() : "");
                map.put("IS_PAPER", cemopMaterialInfoVO.getIsPaper() != null ? cemopMaterialInfoVO.getIsPaper() : "");
                map.put("QUALITICATION_CODE", cemopMaterialInfoVO.getQualiticationCode() != null ? cemopMaterialInfoVO.getQualiticationCode() : "");
                map.put("QUALITY_CODE", cemopMaterialInfoVO.getQualityCode() != null ? cemopMaterialInfoVO.getQualityCode() : "");
                map.put("REPART_ASS", cemopMaterialInfoVO.getRepartAss() != null ? cemopMaterialInfoVO.getRepartAss() : "");
                map.put("APPLY_QTY", cemopMaterialInfoVO.getApplyQty() != null ? cemopMaterialInfoVO.getApplyQty() : "");
                map.put("DELIVERY_QTY", cemopMaterialInfoVO.getDeliveryQty() != null ? cemopMaterialInfoVO.getDeliveryQty() : "");
                map.put("MDS_UNIT_DESC", cemopMaterialInfoVO.getMdsUnitDesc() != null ? cemopMaterialInfoVO.getMdsUnitDesc() : "");
                map.put("DELIVERY_USER", IPUtils.getAccountStr());
                map.put("DELIVERY_DATE", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                map.put("REMARK", cemopMaterialInfoVO.getRemark() != null ? cemopMaterialInfoVO.getRemark() : "");
                map.put("BARCODE", cemopMaterialInfoVO.getBarcode() != null ? cemopMaterialInfoVO.getBarcode() : "");
                map.put("SEND_NUMBER", cemopMaterialInfoVO.getSendNumber() != null ? cemopMaterialInfoVO.getSendNumber() : "");
                map.put("MOM_DELIVERY_PLAN_ID", cemopMaterialInfoVO.getMomDeliveryPlanId() != null ? cemopMaterialInfoVO.getMomDeliveryPlanId() : "");
                map.put("WMS_INV_OUT_ALLOTMENT_ID", cemopMaterialInfoVO.getWmsInvOutAllotmentId() != null ? cemopMaterialInfoVO.getWmsInvOutAllotmentId() : "");
                map.put("MOM_ASS_SETOUT_MATERIAL_ID", cemopMaterialInfoVO.getMomAssSetoutMaterialId() != null ? cemopMaterialInfoVO.getWmsInvOutAllotmentId() : "");
                map.put("RECIEVE_NOTE", cemopMaterialInfoVO.getRecieveNote() != null ? cemopMaterialInfoVO.getRecieveNote() : "");
                map.put("MATERIAL_BZJ", cemopMaterialInfoVO.getMaterialBzj() != null ? cemopMaterialInfoVO.getMaterialBzj() : "");
                map.put("MOM_ASS_AOTASK_ID", cemopMaterialInfoVO.getMomAssAotaskId() != null ? cemopMaterialInfoVO.getMomAssAotaskId() : "");
                map.put("IS_SUBSTITUTE", "");//字段：是否替代品 暂无法提供-待确认
                map.put("MDS_ITEM_ID", cemopMaterialInfoVO.getMdsItemId() != null ? cemopMaterialInfoVO.getMdsItemId() : "");//2025-01-16 新增字段
                map.put("PROCESS_STATUS_NO", cemopMaterialInfoVO.getProcessStatusNo() != null ? cemopMaterialInfoVO.getProcessStatusNo() : "");//2025-01-16 新增字段
                CemopXmlDTO tableDTO = cemopXmlUtil.createTableDTO(cemopMaterialInfoVO.getTableName(), map);
                cemopXmlDTOList.add(tableDTO);
            }
            cemopXmlDTO.setCemopXmlDTOList(cemopXmlDTOList);
            JSONObject xml = cemopXmlUtil.createXml(cemopXmlDTO);
            if (xml == null) {
                log.error("生成XML失败！");
                return new ResponseMsg<>().setResponseBody(null).setMessage("生成XML失败").setRetCode("500");
            }
            return new ResponseMsg<>().setResponseBody(xml).setMessage("101库存发送分拣信息至装配！").setRetCode("200");

        } catch (Exception e) {
            log.error("Error in sendMatchBillInfo: ", e);
            return new ResponseMsg<>().setResponseBody(null).setMessage("系统错误").setRetCode("500");
        }
    }

    /**
     * 101库存撤销配送信息至装配
     *
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> sendCancelDeliveryInfo() {
        // 查询撤销配送信息
        List<CemopCancelDeliveryVO> cemopCancelDeliveryVOS = cemopMapper.selectCemopCancelDeliverInfo();
        if (cemopCancelDeliveryVOS == null || cemopCancelDeliveryVOS.isEmpty()) {
            log.warn("没有发现101库存撤销配送信息至装配数据");
            return new ResponseMsg<>().setResponseBody(null).setMessage("101库存撤销配送信息至装配无数据，请检查数据!").setRetCode("404");
        }

        CemopXmlDTO cemopXmlDTO = new CemopXmlDTO();
        cemopXmlDTO.setXmlType(CemopXmlEnum.CANCEL_DELIVERY.getCode());
        List<CemopXmlDTO> cemopXmlDTOList = new ArrayList<>();
        for (CemopCancelDeliveryVO cemopCancelDeliveryVO : cemopCancelDeliveryVOS) {
            if (cemopCancelDeliveryVO == null) {
                log.warn("分拣信息对象为空，跳过处理");
                continue;
            }
            HashMap map = new HashMap<>();
            map.put("MOM_DELIVER_PLAN_ID", cemopCancelDeliveryVO.getMomDeliverPlanId());
            CemopXmlDTO tableDTO = cemopXmlUtil.createTableDTO(cemopCancelDeliveryVO.getTableName(), map);
            cemopXmlDTOList.add(tableDTO);
        }
        cemopXmlDTO.setCemopXmlDTOList(cemopXmlDTOList);
        JSONObject xml = cemopXmlUtil.createXml(cemopXmlDTO);
        if (xml == null) {
            log.error("生成XML失败！");
            return new ResponseMsg<>().setResponseBody(null).setMessage("生成XML失败").setRetCode("500");
        }
        return new ResponseMsg<>().setResponseBody(xml).setMessage("101库存撤销配送信息至装配成功！").setRetCode("200");
    }
//    /**
//     * 装配系统工人退库物料至101库存
//     *
//     * @return
//     */
//    @Transactional
//    @Override
//    public ResponseMsg<Object> getWorkersReturnMaterials(JSONObject jsonObject) throws FileNotFoundException, ParseException {
//        log.info("装配系统工人退库物料至101库存操作数据" + jsonObject);
//        HashMap<Object, Object> map1 = new HashMap<>();
//        String fileUrl = jsonObject.get("fileUrl").toString();
//        List<File> files = cemopXmlUtil.downloadAndExtractXMLFiles(fileUrl);
//        //解析xml文件
//        FileInputStream fileInputStream = null;
//        fileInputStream = new FileInputStream(files.get(0));
//        XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
//        List<Map<String, String>> list = xmlReadUtil.getAttributesByTagName("MOM_ASS_MATERIAL_RECEIVE");
//        //将XML数据转成DTO
//        List<CemopWorkersReturnMaterialsDTO> cemopWorkersReturnMaterialsDTOS = new ArrayList<>();
//
//        for (Map<String, String> map : list) {
//            CemopWorkersReturnMaterialsDTO cemopWorkersReturnMaterialsDTO1 = new CemopWorkersReturnMaterialsDTO();
//            xmlReadUtil.mapToDTO(map, cemopWorkersReturnMaterialsDTO1);
//            cemopWorkersReturnMaterialsDTOS.add(cemopWorkersReturnMaterialsDTO1);
//        }
//        log.info("解析完成后的数据" + cemopWorkersReturnMaterialsDTOS);
//        //处理当前库的数据
//        for (CemopWorkersReturnMaterialsDTO cemopWorkersReturnMaterialsDTO : cemopWorkersReturnMaterialsDTOS) {
//            //修改交接单的数据
//            String momDeliveryPlanId = cemopWorkersReturnMaterialsDTO.getMOM_DELIVERY_PLAN_ID();
//            WmsDeliveryPlan wmsDeliveryPlan = wmsDeliveryPlanService.getById(momDeliveryPlanId);
//            wmsDeliveryPlan.setQualityCode(cemopWorkersReturnMaterialsDTO.getQUALITY_CODE());
//            wmsDeliveryPlan.setSubstituteCode(cemopWorkersReturnMaterialsDTO.getBILL_NO());
//            wmsDeliveryPlan.setMesCheckQualiticationId(cemopWorkersReturnMaterialsDTO.getCERTIFICATE_NO());
//            wmsDeliveryPlan.setAttribute13(cemopWorkersReturnMaterialsDTO.getOPER_DATE());
//            wmsDeliveryPlan.setAttribute12(cemopWorkersReturnMaterialsDTO.getOPER_QTY());
//            wmsDeliveryPlan.setAttribute11(cemopWorkersReturnMaterialsDTO.getREJECT_REASON());
//            wmsDeliveryPlan.setAttribute9(cemopWorkersReturnMaterialsDTO.getOPER_USER());
//            wmsDeliveryPlan.setAttribute19(cemopWorkersReturnMaterialsDTO.getITEM_TYPE());
//            wmsDeliveryPlan.setAttribute14("1");
//            wmsDeliveryPlan.setDeliveryStatus("4");
//            log.info("交接单的数据" + wmsDeliveryPlan);
//            wmsDeliveryPlanService.updateById(wmsDeliveryPlan);
//            //创建退库单的数据
//            WmsReturnApply wmsReturnApply = new WmsReturnApply();
//            wmsReturnApply.setWmsReturnApplyId(IdUtil.simpleUUID());
//            wmsReturnApply.setWmsDeliveryPlanId(cemopWorkersReturnMaterialsDTO.getMOM_DELIVERY_PLAN_ID());
//            wmsReturnApply.setReturnType("1");
//            wmsReturnApply.setItemCode(cemopWorkersReturnMaterialsDTO.getMDS_ITEM_CODE());
//            wmsReturnApply.setQualityCode(cemopWorkersReturnMaterialsDTO.getQUALITY_CODE());
//            wmsReturnApply.setBillNo(cemopWorkersReturnMaterialsDTO.getBILL_NO());
//            wmsReturnApply.setMesCheckQualiticationId(cemopWorkersReturnMaterialsDTO.getCERTIFICATE_NO());
//            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
//            Date date = fmt.parse(cemopWorkersReturnMaterialsDTO.getOPER_DATE());
//            wmsReturnApply.setLastUpdateDate(date);
//            wmsReturnApply.setReturnQty(new BigDecimal(cemopWorkersReturnMaterialsDTO.getOPER_QTY()));
//            wmsReturnApply.setLastUpdatedBy(cemopWorkersReturnMaterialsDTO.getOPER_USER());
//            wmsReturnApply.setRejectReason(cemopWorkersReturnMaterialsDTO.getREJECT_REASON());
//            log.info("退库单数据" + wmsReturnApply);
//            wmsReturnApplyService.save(wmsReturnApply);
//            //修改AO物料配套信息
//            if (wmsDeliveryPlan.getAttribute1() != null && wmsDeliveryPlan.getAttribute1() != "") {
//                LambdaUpdateWrapper<MsAoMatchInfo> updateWrapper = new LambdaUpdateWrapper<>();
//                updateWrapper.set(MsAoMatchInfo::getLastUpdateDate, date);
//                updateWrapper.set(MsAoMatchInfo::getReturnQty, cemopWorkersReturnMaterialsDTO.getOPER_QTY());
//                updateWrapper.in(MsAoMatchInfo::getMsAoMatchInfoId, wmsDeliveryPlan.getAttribute1());
//                log.info("修改matchInfoId" + wmsReturnApply);
//                iMsAoMatchInfoNewService.update(updateWrapper);
//            }
//            map1.put("fileUrl", fileUrl);
//            map1.put("xmlList", list);
//            CemopAoRevokesOutboundDTO cemopAoRevokesOutboundDTO = new CemopAoRevokesOutboundDTO();
//            cemopAoRevokesOutboundDTO.setMomWmsInvOutAllotmentId(wmsDeliveryPlan.getWmsInvOutAllotmentId());
//            cemopAoRevokesOutboundDTO.setUserId(cemopWorkersReturnMaterialsDTO.getOPER_USER());
//            sendAoRevokesOutbound(cemopAoRevokesOutboundDTO);
//        }
//        return new ResponseMsg<>().setMessage("装配系统工人退库物料至101库存操作成功").setResponseBody(map1);
//    }

    /**
     * 装配系统工人退库物料至101库存
     *
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> getWorkersReturnMaterials(JSONObject jsonObject) throws FileNotFoundException, ParseException {
        log.info("装配系统工人退库物料至101库存操作数据" + jsonObject);
        jsonObject.put("description","装配系统工人退库物料");
        HashMap<Object, Object> map1 = new HashMap<>();
        try {
            String fileUrl = jsonObject.get("fileUrl").toString();
            List<File> files = cemopXmlUtil.downloadAndExtractXMLFiles(fileUrl);
            //解析xml文件
            FileInputStream fileInputStream = null;
            fileInputStream = new FileInputStream(files.get(0));
            XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
            List<Map<String, String>> list = xmlReadUtil.getAttributesByTagName("MOM_ASS_MATERIAL_RECEIVE");
            //将XML数据转成DTO
            List<CemopWorkersReturnMaterialsDTO> cemopWorkersReturnMaterialsDTOS = new ArrayList<>();

            for (Map<String, String> map : list) {
                CemopWorkersReturnMaterialsDTO cemopWorkersReturnMaterialsDTO1 = new CemopWorkersReturnMaterialsDTO();
                xmlReadUtil.mapToDTO(map, cemopWorkersReturnMaterialsDTO1);
                cemopWorkersReturnMaterialsDTOS.add(cemopWorkersReturnMaterialsDTO1);
            }
            log.info("解析完成后的数据" + cemopWorkersReturnMaterialsDTOS);
            //处理当前库的数据
            for (CemopWorkersReturnMaterialsDTO cemopWorkersReturnMaterialsDTO : cemopWorkersReturnMaterialsDTOS) {
                //创建退库单的数据
                WmsReturnApply wmsReturnApply = new WmsReturnApply();
                wmsReturnApply.setWmsReturnApplyId(IdUtil.simpleUUID());
                wmsReturnApply.setWmsDeliveryPlanId(cemopWorkersReturnMaterialsDTO.getMOM_DELIVERY_PLAN_ID());
                wmsReturnApply.setReturnType("1");
                wmsReturnApply.setReturnStatus("1");
                wmsReturnApply.setItemCode(cemopWorkersReturnMaterialsDTO.getMDS_ITEM_CODE());
                wmsReturnApply.setQualityCode(cemopWorkersReturnMaterialsDTO.getQUALITY_CODE());
                wmsReturnApply.setBillNo(cemopWorkersReturnMaterialsDTO.getBILL_NO());
                wmsReturnApply.setMesCheckQualiticationId(cemopWorkersReturnMaterialsDTO.getCERTIFICATE_NO());
                DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                Date date = fmt.parse(cemopWorkersReturnMaterialsDTO.getOPER_DATE());
                wmsReturnApply.setLastUpdateDate(date);
                wmsReturnApply.setReturnQty(new BigDecimal(cemopWorkersReturnMaterialsDTO.getOPER_QTY()));
                wmsReturnApply.setLastUpdatedBy(cemopWorkersReturnMaterialsDTO.getOPER_USER());
                wmsReturnApply.setRejectReason(cemopWorkersReturnMaterialsDTO.getREJECT_REASON());
                log.info("退库单数据" + wmsReturnApply);
                wmsReturnApplyService.save(wmsReturnApply);
                map1.put("fileUrl", fileUrl);
                map1.put("xmlList", list);
            }
            jsonObject.put("msg","装配系统工人退库物料至101库存操作成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setMessage("装配系统工人退库物料至101库存操作成功").setResponseBody(map1);
        } catch (FileNotFoundException e) {
            jsonObject.put("msg","失败："+e);
            sendSortBackResult(jsonObject);
            jsonObject.put("status","3");
            throw new RuntimeException(e);
        } catch (ParseException e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * 装配系统工人撤销移交物料至101库存
     *
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> getRevocationTransfer(JSONObject jsonObject) {
        log.info("装配系统工人撤销移交物料数据" + jsonObject);
        jsonObject.put("description","装配系统工人撤销移交物料");
        HashMap<Object, Object> map1 = new HashMap<>();
        try {
            String fileUrl = jsonObject.get("fileUrl").toString();
            List<File> files = cemopXmlUtil.downloadAndExtractXMLFiles(fileUrl);
            //解析xml文件
            FileInputStream fileInputStream = null;
            fileInputStream = new FileInputStream(files.get(0));
            XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
            List<Map<String, String>> list = xmlReadUtil.getAttributesByTagName("MOM_ASS_ACTUAL_MATERIAL");
            //将XML数据转成DTO
            List<CemopWorkersReturnMaterialsDTO> cemopWorkersReturnMaterialsDTOS = new ArrayList<>();
            log.info("解析完成后的数据" + cemopWorkersReturnMaterialsDTOS);
            for (Map<String, String> map : list) {
                CemopWorkersReturnMaterialsDTO cemopWorkersReturnMaterialsDTO1 = new CemopWorkersReturnMaterialsDTO();
                xmlReadUtil.mapToDTO(map, cemopWorkersReturnMaterialsDTO1);
                cemopWorkersReturnMaterialsDTOS.add(cemopWorkersReturnMaterialsDTO1);
            }
            //修改交接单数据
            for (CemopWorkersReturnMaterialsDTO cemopWorkersReturnMaterialsDTO : cemopWorkersReturnMaterialsDTOS) {
                String momDeliveryPlanId = cemopWorkersReturnMaterialsDTO.getMOM_DELIVERY_PLAN_ID();
                WmsDeliveryPlan wmsDeliveryPlan = wmsDeliveryPlanService.getById(momDeliveryPlanId);
                wmsDeliveryPlan.setDeliveryStatus("1");
                wmsDeliveryPlanService.updateById(wmsDeliveryPlan);
            }
            map1.put("fileUrl", fileUrl);
            map1.put("xmlList", list);
            jsonObject.put("msg","装配系统工人撤销移交物料至101库存操作成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
        } catch (FileNotFoundException e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
        return new ResponseMsg<>().setMessage("装配系统工人撤销移交物料至101库存操作成功").setResponseBody(map1);
    }

    /**
     * 装配系统工人二次配套物料至101库存
     *
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> receiveSecondMatch(@RequestBody JSONObject jsonObject) {
        log.info("======================Cemop下发二次配套物料=========================");
        HashMap map = new HashMap();
        jsonObject.put("description","装配系统工人二次配套物料");
        //获取文件url
        String fileUrl = jsonObject.get("fileUrl").toString();
        log.info("=========================下载zip文件并获取File文件==========================");
        List<File> files = cemopXmlUtil.downloadAndExtractXMLFile(fileUrl);
        //解析xml文件，拿到二次配套物料内容（物料）
        try {
            FileInputStream fileInputStream = new FileInputStream(files.get(0));
            XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
            RootDTO rootDTO = new RootDTO();
//            List<Map<String, String>> list1 = xmlReadUtil.getAttributesByTagName("MOM_MATERIAL_RECL_L");
            List<Map<String, String>> list1 = xmlReadUtil.getAttributesByTagName("MOM_ASS_MATERIAL_RECEIVE");
            List<SecondMatchDTO> secondMatchDTOS = new ArrayList<>();
            for (Map<String, String> hashMap : list1) {
                SecondMatchDTO secondMatchDTO = new SecondMatchDTO();
                xmlReadUtil.mapToDTO(hashMap, secondMatchDTO);
                secondMatchDTOS.add(secondMatchDTO);
            }
            for (SecondMatchDTO secondMatchDTO : secondMatchDTOS) {
                //交接单表
                WmsDeliveryPlan wmsDeliveryPlans = new WmsDeliveryPlan();
                wmsDeliveryPlans.setAttribute13(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")); //退库时间
                wmsDeliveryPlans.setAttribute12(secondMatchDTO.getRECE_QTY());
//                wmsDeliveryPlans.setAttribute5(secondMatchDTO.getMDS_ITEM_ID());
                wmsDeliveryPlans.setWmsDeliveryPlanId(secondMatchDTO.getMOM_DELIVERY_PLAN_ID());
                //更新交接单 MS_AO_MATCH_INFO
                wmsDeliveryPlanService.updateById(wmsDeliveryPlans);
                //更新MS_AO_MATCH_INFO配套结果表
                cemopMapper.materialSecondMatchInfo(secondMatchDTO.getMOM_DELIVERY_PLAN_ID(), secondMatchDTO.getRECE_QTY());
                //插入二次配套表 MS_SECOND_MATCH_INFO
                MsSecondMatchInfo msSecondMatchInfo = new MsSecondMatchInfo();
                msSecondMatchInfo.setWmsDeliveryPlanId(secondMatchDTO.getMOM_DELIVERY_PLAN_ID());
                msSecondMatchInfo.setSecondApplyUsercode(secondMatchDTO.getReceUser());
                Date date = DateUtil.parse(secondMatchDTO.getRECE_DATE(), "yyyy-MM-dd HH:mm:ss");
                msSecondMatchInfo.setMatchDate(date);
                BigDecimal secondMatchQty = new BigDecimal(secondMatchDTO.getRECE_QTY());
                msSecondMatchInfo.setSecondMatchQty(secondMatchQty);
                msSecondMatchInfoService.save(msSecondMatchInfo);

            }
            map.put("fileUrl", fileUrl);
            map.put("xmlList", list1);
            jsonObject.put("msg","配系统工人二次配套物料至101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(map).setMessage("配系统工人二次配套物料至101库存成功!").setRetCode("200");
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(null).setMessage("系统错误").setRetCode("500");
        }
    }

    /**
     * 装配系统扫码移交至101库存
     *
     * @param jsonObject
     * @return
     */
    @Override
    @Transactional
    public ResponseMsg<Object> receiveMaterialDelivery(JSONObject jsonObject) {
        log.info("======================装配系统扫码移交至101库存=========================");
        jsonObject.put("description","装配系统扫码移交");
        HashMap map = new HashMap();
        //获取文件url
        String fileUrl = jsonObject.get("fileUrl").toString();
        List<File> files = cemopXmlUtil.downloadAndExtractXMLFile(fileUrl);
        //解析xml文件，拿到扫码移交内容
        try {
            FileInputStream fileInputStream = new FileInputStream(files.get(0));
            XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
//            List<Map<String, String>> shreddedSheetList = xmlReadUtil.getAttributesByTagName("MOM_ASS_ACTUAL_MATERIAL");
            List<Map<String, String>> shreddedSheetList = xmlReadUtil.getAttributesByTagName("MOM_ASS_MATERIAL_RECEIVE");
            List<ShopMaterialDeliveryDTO> shreddedSheetDTOS = new ArrayList<>();
            for (Map<String, String> hashMap : shreddedSheetList) {
                ShopMaterialDeliveryDTO shopMaterialDeliveryDTO = new ShopMaterialDeliveryDTO();
                xmlReadUtil.mapToDTO(hashMap, shopMaterialDeliveryDTO);
                shreddedSheetDTOS.add(shopMaterialDeliveryDTO);
            }
            for (ShopMaterialDeliveryDTO shopMaterialDeliveryDTO : shreddedSheetDTOS) {
                LambdaQueryWrapper<WmsDeliveryPlan> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmsDeliveryPlan::getWmsDeliveryPlanId, shopMaterialDeliveryDTO.getMOM_DELIVERY_PLAN_ID());
                WmsDeliveryPlan wmsDeliveryPlan = wmsDeliveryPlanService.getOne(queryWrapper);
                if (shopMaterialDeliveryDTO.getSEND_DATE() != null && !shopMaterialDeliveryDTO.getSEND_DATE().isEmpty()) {
                    Date date = DateUtil.parse(shopMaterialDeliveryDTO.getSEND_DATE(), "yyyy-MM-dd HH:mm:ss");
                    wmsDeliveryPlan.setDeliveryDate(date);
                }
                else {
                    wmsDeliveryPlan.setDeliveryDate(new Date());
                }
                String deliverQty = shopMaterialDeliveryDTO.getDELIVER_QTY();
                BigDecimal bigDecimalQty = new BigDecimal(deliverQty);
                wmsDeliveryPlan.setDeliveryQty(bigDecimalQty);
                wmsDeliveryPlan.setDeliveryEmpCode(shopMaterialDeliveryDTO.getSEND_USER());
                wmsDeliveryPlan.setDeliveryStatus("2");
                wmsDeliveryPlan.setWmsDeliveryPlanId(shopMaterialDeliveryDTO.getMOM_DELIVERY_PLAN_ID());
//                wmsDeliveryPlan.setWmsItemInventoryId(shopMaterialDeliveryDTO.getMOM_ASS_MATERIAL_RECEIVE_ID());//实际接收物料表主键-暂设置为台账ID-待确认
                //更新交接单
                wmsDeliveryPlanService.updateById(wmsDeliveryPlan);
                //发送到Cemop装配系统
                CemopAoMatchingOutboundDTO cemopAoMatchingOutboundDTO = new CemopAoMatchingOutboundDTO();
                cemopAoMatchingOutboundDTO.setMomWmsInvOutAllotmentId(wmsDeliveryPlan.getAttribute6Desc());
                cemopAoMatchingOutboundDTO.setMomWmsDeliveryPlanId(shopMaterialDeliveryDTO.getMOM_DELIVERY_PLAN_ID());
//                cemopAoMatchingOutboundDTO.setNewCertificate(wmsDeliveryPlan.getMesCheckQualiticationId());
//                cemopAoMatchingOutboundDTO.setQty(deliverQty);
                cemopAoMatchingOutboundDTO.setUserId(shopMaterialDeliveryDTO.getSEND_USER());
                sendAoMatchingOutbound(cemopAoMatchingOutboundDTO);
            }
            jsonObject.put("msg","装配系统扫码移交至101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonObject).setMessage("装配系统扫码移交至101库存成功!").setRetCode("200");

        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonObject).setMessage("系统错误").setRetCode("500");
        }
    }

    /**
     * 101扫码移交发送Cemop
     *
     * @param toolCodes
     * @return
     */
    @Override
    public ResponseMsg<Object> shopMaterialDelivery(List<String> toolCodes) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("description","101扫码移交发送Cemop");
        HashMap map = new HashMap();
        try {
            LambdaQueryWrapper<WmsDeliveryPlan> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(WmsDeliveryPlan::getSourceType, "3");
            queryWrapper1.eq(WmsDeliveryPlan::getDeliveryStatus, "1");
            queryWrapper1.in(WmsDeliveryPlan::getAttribute6, toolCodes);
            List<WmsDeliveryPlan> wmsDeliveryPlans = wmsDeliveryPlanService.list(queryWrapper1);
            HashMap hashmap = msDeliveryCrewDao.msDeliveryCrewFindName("AGV");
            String userid = hashmap.get("deliveryEmpCode").toString();
            ObjectMapper mapper = new ObjectMapper();
            String CemopUrl = environment.getProperty("cemopUrl.shopMaterialDelivery");
            List<CemopAoMatchingOutboundDTO> cemopAoMatchingOutboundDTOS = new ArrayList<>();
            List<CemopXmlDTO> cemopXmlDTOList = new ArrayList<>();
            CemopXmlDTO cemopXmlDTO = new CemopXmlDTO();
            cemopXmlDTO.setXmlType(CemopXmlEnum.SHOP_MATERIAL_DELIVERY.getCode());
            for (WmsDeliveryPlan wmsDeliveryPlan : wmsDeliveryPlans) {
                CemopAoMatchingOutboundDTO cemopAoMatchingOutboundDTO = new CemopAoMatchingOutboundDTO();
                cemopAoMatchingOutboundDTO.setMomWmsInvOutAllotmentId(wmsDeliveryPlan.getAttribute6Desc());
                cemopAoMatchingOutboundDTO.setMomWmsDeliveryPlanId(wmsDeliveryPlan.getWmsDeliveryPlanId());
                cemopAoMatchingOutboundDTO.setQty(wmsDeliveryPlan.getDeliveryQty().toString());
                cemopAoMatchingOutboundDTO.setUserId(userid);
                cemopAoMatchingOutboundDTOS.add(cemopAoMatchingOutboundDTO);

                Map<String, String> hashMap = new HashMap();
                hashMap.put("MOM_DELIVERY_PLAN_ID", wmsDeliveryPlan.getWmsDeliveryPlanId());
                hashMap.put("SEND_USER", userid);
                hashMap.put("SEND_DATE", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                hashMap.put("DELIVER_QTY", wmsDeliveryPlan.getDeliveryQty().toString());
                CemopXmlDTO tableDTO = cemopXmlUtil.createTableDTO("MOM_ASS_ACTUAL_MATERIAL", hashMap);
                cemopXmlDTOList.add(tableDTO);
            }
            LambdaUpdateWrapper<WmsDeliveryPlan> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(WmsDeliveryPlan::getDeliveryEmpCode, hashmap.get("deliveryEmpCode").toString());
            updateWrapper.set(WmsDeliveryPlan::getDeliveryStatus, "2");
            updateWrapper.set(WmsDeliveryPlan::getDeliveryDate, new Date());
            updateWrapper.eq(WmsDeliveryPlan::getSourceType, "3");
            updateWrapper.eq(WmsDeliveryPlan::getDeliveryStatus, "1");
            updateWrapper.in(WmsDeliveryPlan::getAttribute6, toolCodes);
            wmsDeliveryPlanService.update(updateWrapper);
            String zipUrl = compressedFilesEditor.generateZip(mapper.writeValueAsString(cemopAoMatchingOutboundDTOS));
            cemopXmlDTO.setCemopXmlDTOList(cemopXmlDTOList);
            JSONObject xml = cemopXmlUtil.createXml(cemopXmlDTO);
            compressedFilesEditor.fileSend(cemopAoMatchingOutboundDTOS,zipUrl, CemopUrl,"101扫码移交至装配");
            if (xml == null) {
                log.error("生成XML失败！");
                return new ResponseMsg<>().setResponseBody(null).setMessage("生成XML失败").setRetCode("500");
            }
            jsonObject.put("msg","101扫码移交至装配成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonObject).setMessage("101扫码移交至装配成功!").setRetCode("200");
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(jsonObject).setMessage("系统错误").setRetCode("500");
        }
    }


    /**
     * 装配系统工艺变更下发至101库存
     *
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResponseMsg<Object> getChangeProcess(JSONObject jsonObject) throws FileNotFoundException {
        log.info("装配系统工艺变更数据" + jsonObject);
        jsonObject.put("description","装配系统工艺变更下发");
        try {
            //获取文件url
            String fileUrl = jsonObject.get("fileUrl").toString();
            List<File> files = cemopXmlUtil.downloadAndExtractXMLFile(fileUrl);
            //解析xml文件，拿到扫码移交内容
            FileInputStream fileInputStream = new FileInputStream(files.get(0));
            XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
            RootDTO rootDTO = new RootDTO();
            List<Map<String, String>> list = xmlReadUtil.getAttributesByTagName("MOM_ASS_SETOUT_MATERIAL");
            List<MomAssSetoutMaterialDTO> momAssSetoutMaterialDTOS = new ArrayList<>();
            for (Map<String, String> map : list) {
                MomAssSetoutMaterialDTO momAssSetoutMaterialDTO = new MomAssSetoutMaterialDTO();
                xmlReadUtil.mapToDTO(map, momAssSetoutMaterialDTO);
                momAssSetoutMaterialDTOS.add(momAssSetoutMaterialDTO);
            }
            log.info("解析完成后的数据" + momAssSetoutMaterialDTOS);
            //取所有AO号，根据AO处理数据
            List<String> aoList = momAssSetoutMaterialDTOS.stream().map(MomAssSetoutMaterialDTO::getMOM_ASS_AOTASK_ID).distinct().collect(Collectors.toList());
            //取所有需求物料
            QueryWrapper<MsAoMatchBill> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("ms_task_ao_id", aoList);
            List<MsAoMatchBill> msAoMatchBills = msAoMatchBillMapper.selectList(queryWrapper);
            List<MsAoMatchBill> addMsAoMatchBills = new ArrayList<>();
            List<MsAoMatchBill> UpdMsAoMatchBills = new ArrayList<>();
            List<MsAoMatchBill> DelMsAoMatchBills = new ArrayList<>();
            //遍历AO编号，根据AO编号更新需求物料
            for (String ao : aoList) {
                //将数据库中原有的数据进行修改操作，根据AO编号、需求物料编号等条件进行匹配
                List<MsAoMatchBill> msAoMatchBills1 = msAoMatchBills.stream().filter(msAoMatchBill -> msAoMatchBill.getMsTaskAoId().equals(ao)).collect(Collectors.toList());
                momAssSetoutMaterialDTOS.stream().filter(a -> a.getMOM_ASS_AOTASK_ID().equals(ao)).forEach(momAssSetoutMaterialDTO -> {
                    List<MsAoMatchBill> updmsAoMatchBill = msAoMatchBills1.stream().filter(s ->
                            Objects.equals(s.getProductCode(), momAssSetoutMaterialDTO.getMODLS_ECD()) &&
                                    Objects.equals(s.getBatchNo(), momAssSetoutMaterialDTO.getBCH_NO()) &&
                                    Objects.equals(s.getPlaneNo(), momAssSetoutMaterialDTO.getSORTIE_NO()) &&
                                    Objects.equals(s.getItemCode(), momAssSetoutMaterialDTO.getMDS_ITEM_CODE()) &&
                                    Objects.equals(s.getPlanId(), momAssSetoutMaterialDTO.getPLAN_ID()) &&
                                    Objects.equals(s.getRepartAss(), momAssSetoutMaterialDTO.getREPART_ASS()) &&
                                    Objects.equals(s.getAoCode(), momAssSetoutMaterialDTO.getAO_NO())
                    ).collect(Collectors.toList());
                    //判断此物料是否存在于数据库中，如果没有则新增
                    if (updmsAoMatchBill.size() == 0) {
                        MsAoMatchBill addmsAoMatchBill = new MsAoMatchBill();
                        addmsAoMatchBill.setMsAoMatchBillId(UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
                        addmsAoMatchBill.setProductCode(momAssSetoutMaterialDTO.getMODLS_ECD());
                        addmsAoMatchBill.setBatchNo(momAssSetoutMaterialDTO.getBCH_NO());
                        addmsAoMatchBill.setPlaneNo(momAssSetoutMaterialDTO.getSORTIE_NO());
                        addmsAoMatchBill.setAoCode(momAssSetoutMaterialDTO.getAO_NO());
                        addmsAoMatchBill.setItemCode(momAssSetoutMaterialDTO.getMDS_ITEM_CODE());
                        addmsAoMatchBill.setItemName(momAssSetoutMaterialDTO.getMDS_ITEM_NAME());
                        addmsAoMatchBill.setItemQty(new BigDecimal(momAssSetoutMaterialDTO.getREQUIRE_QTY()));
                        addmsAoMatchBill.setWorkplaceCode(momAssSetoutMaterialDTO.getWORKPACKAGE_CODE());
                        addmsAoMatchBill.setCreatedBy("");
                        addmsAoMatchBill.setCreationDate(new Date());
                        addmsAoMatchBill.setLastUpdatedBy("");
                        addmsAoMatchBill.setLastUpdateDate(new Date());
                        addmsAoMatchBill.setArtChangeType("A");
                        addmsAoMatchBill.setIsArtChange("Y");
                        addmsAoMatchBill.setArtChangeNum(new BigDecimal(momAssSetoutMaterialDTO.getREQUIRE_QTY()));
                        addmsAoMatchBill.setItemType(momAssSetoutMaterialDTO.getMDS_ITEM_TYPE());
                        addmsAoMatchBill.setPlanId(momAssSetoutMaterialDTO.getPLAN_ID());
                        addmsAoMatchBill.setRepartAss(momAssSetoutMaterialDTO.getREPART_ASS());
                        addMsAoMatchBills.add(addmsAoMatchBill);
                    } else if (updmsAoMatchBill.size() > 0) //如果数据库中有此物料，则更新此物料信息
                    {
                        for (MsAoMatchBill msAoMatchBill : updmsAoMatchBill) {
                            msAoMatchBill.setArtChangeType("U");
                            msAoMatchBill.setIsArtChange("Y");
                            if (momAssSetoutMaterialDTO.getREQUIRE_QTY() >= 0) {
                                msAoMatchBill.setArtChangeNum(msAoMatchBill.getItemQty());
                                msAoMatchBill.setItemQty(new BigDecimal(momAssSetoutMaterialDTO.getREQUIRE_QTY()));
                            }
                            msAoMatchBill.setLastUpdateDate(new Date());
                            msAoMatchBillMapper.updateById(msAoMatchBill);
                        }
                        msAoMatchBills.remove(updmsAoMatchBill);
                    }
                });
            }
            //更新数据库
            iMsAoMatchBillService.saveBatch(addMsAoMatchBills);
            //将处理过的数据进行清理后，后面在将剩余的数据进行删除（修改）
            for (MsAoMatchBill msAoMatchBill : msAoMatchBills) {
                msAoMatchBill.setArtChangeType("D");
                msAoMatchBill.setIsArtChange("Y");
                msAoMatchBill.setLastUpdateDate(new Date());
                msAoMatchBillMapper.updateById(msAoMatchBill);
            }
            jsonObject.put("msg","装配系统工艺变更下发至101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(null).setMessage("装配系统工艺变更下发至101库存!").setRetCode("200");
        } catch (FileNotFoundException e) {
            jsonObject.put("status","3");
            jsonObject.put("msg","失败："+e);
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

//    /**
//     *101库存同意工人退库物料通知装配
//     * @param jsonObject
//     * @return
//     */
//    @Override
//    public ResponseMsg<Object> sendAgreeReturnMaterials(JSONObject jsonObject) throws FileNotFoundException, ParseException {
//        log.info("装配系统工人退库物料至101库存操作数据" + jsonObject);
//        HashMap<Object, Object> map1 = new HashMap<>();
//        String fileUrl = jsonObject.get("fileUrl").toString();
//        List<File> files = cemopXmlUtil.downloadAndExtractXMLFiles(fileUrl);
//        //解析xml文件
//        FileInputStream fileInputStream = null;
//        fileInputStream = new FileInputStream(files.get(0));
//        XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
//        List<Map<String, String>> list = xmlReadUtil.getAttributesByTagName("MOM_ASS_MATERIAL_RECEIVE");
//        //将XML数据转成DTO
//        List<CemopWorkersReturnMaterialsDTO> cemopWorkersReturnMaterialsDTOS = new ArrayList<>();
//
//        for (Map<String, String> map : list) {
//            CemopWorkersReturnMaterialsDTO cemopWorkersReturnMaterialsDTO1 = new CemopWorkersReturnMaterialsDTO();
//            xmlReadUtil.mapToDTO(map, cemopWorkersReturnMaterialsDTO1);
//            cemopWorkersReturnMaterialsDTOS.add(cemopWorkersReturnMaterialsDTO1);
//        }
//        log.info("解析完成后的数据" + cemopWorkersReturnMaterialsDTOS);
//        //处理当前库的数据
//        for (CemopWorkersReturnMaterialsDTO cemopWorkersReturnMaterialsDTO : cemopWorkersReturnMaterialsDTOS) {
//            //修改交接单的数据
//            String momDeliveryPlanId = cemopWorkersReturnMaterialsDTO.getMOM_DELIVERY_PLAN_ID();
//            WmsDeliveryPlan wmsDeliveryPlan = wmsDeliveryPlanService.getById(momDeliveryPlanId);
//            wmsDeliveryPlan.setQualityCode(cemopWorkersReturnMaterialsDTO.getQUALITY_CODE());
//            wmsDeliveryPlan.setSubstituteCode(cemopWorkersReturnMaterialsDTO.getBILL_NO());
//            wmsDeliveryPlan.setMesCheckQualiticationId(cemopWorkersReturnMaterialsDTO.getCERTIFICATE_NO());
//            wmsDeliveryPlan.setAttribute13(cemopWorkersReturnMaterialsDTO.getOPER_DATE());
//            wmsDeliveryPlan.setAttribute12(cemopWorkersReturnMaterialsDTO.getOPER_QTY());
//            wmsDeliveryPlan.setAttribute11(cemopWorkersReturnMaterialsDTO.getREJECT_REASON());
//            wmsDeliveryPlan.setAttribute9(cemopWorkersReturnMaterialsDTO.getOPER_USER());
//            wmsDeliveryPlan.setAttribute19(cemopWorkersReturnMaterialsDTO.getITEM_TYPE());
//            wmsDeliveryPlan.setAttribute14("1");
//            wmsDeliveryPlan.setDeliveryStatus("4");
//            log.info("交接单的数据" + wmsDeliveryPlan);
//            wmsDeliveryPlanService.updateById(wmsDeliveryPlan);
//            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
//            Date date = fmt.parse(cemopWorkersReturnMaterialsDTO.getOPER_DATE());
//            //修改AO物料配套信息
//            if (wmsDeliveryPlan.getAttribute1() != null && wmsDeliveryPlan.getAttribute1() != "") {
//                LambdaUpdateWrapper<MsAoMatchInfo> updateWrapper = new LambdaUpdateWrapper<>();
//                updateWrapper.set(MsAoMatchInfo::getLastUpdateDate, date);
//                updateWrapper.set(MsAoMatchInfo::getReturnQty, cemopWorkersReturnMaterialsDTO.getOPER_QTY());
//                updateWrapper.in(MsAoMatchInfo::getMsAoMatchInfoId, wmsDeliveryPlan.getAttribute1());
//                log.info("修改matchInfoId" + wmsReturnApply);
//                iMsAoMatchInfoNewService.update(updateWrapper);
//            }
//            map1.put("fileUrl", fileUrl);
//            map1.put("xmlList", list);
//            CemopAoRevokesOutboundDTO cemopAoRevokesOutboundDTO = new CemopAoRevokesOutboundDTO();
//            cemopAoRevokesOutboundDTO.setMomWmsInvOutAllotmentId(wmsDeliveryPlan.getWmsInvOutAllotmentId());
//            cemopAoRevokesOutboundDTO.setUserId(cemopWorkersReturnMaterialsDTO.getOPER_USER());
//            sendAoRevokesOutbound(cemopAoRevokesOutboundDTO);
//            //通知Cemop装配系统
//
//        }
//        return new ResponseMsg<>().setMessage("装配系统工人退库物料至101库存操作成功").setResponseBody(map1);
//    }
//
//    /**
//     *101库存驳回工人退库物料通知装配
//     * @param jsonObject
//     * @return
//     */
//    @Override
//    public ResponseMsg<Object> sendRejectReturnMaterials(JSONObject jsonObject) {
//        return null;
//    }
//
//    /**
//     * 101库存同意物料二次配套通知装配
//     * @param msSecondMatchInfo
//     * @return
//     */
//    @Override
//    public ResponseMsg<Object> sendAgreeSecondMatch(MsSecondMatchInfo msSecondMatchInfo) {
//        log.info("101库存同意物料二次配套通知装配数据" + msSecondMatchInfo);
//        WmsDeliveryPlan wmsDeliveryPlans = new WmsDeliveryPlan();
//        wmsDeliveryPlans.setAttribute13(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")); //退库时间
//        wmsDeliveryPlans.setAttribute12(String.valueOf(msSecondMatchInfo.getSecondMatchQty()));
//        wmsDeliveryPlans.setWmsDeliveryPlanId(msSecondMatchInfo.getWmsDeliveryPlanId());
//        //更新交接单 MS_AO_MATCH_INFO
//        wmsDeliveryPlanService.updateById(wmsDeliveryPlans);
//        //更新MS_AO_MATCH_INFO配套结果表
//        cemopMapper.materialSecondMatchInfo(msSecondMatchInfo.getWmsDeliveryPlanId(), String.valueOf(msSecondMatchInfo.getSecondMatchQty()));
//        CemopXmlDTO cemopXmlDTO = new CemopXmlDTO();
//        cemopXmlDTO.setXmlType(CemopXmlEnum.AGREE_SECOND_MATCH.getCode());
//        //使用交接单ID查询退库单
//        LambdaQueryWrapper<WmsReturnApply> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(WmsReturnApply::getWmsDeliveryPlanId, msSecondMatchInfo.getWmsDeliveryPlanId());
//        WmsReturnApply wmsReturnApply = iWmsReturnApplyService.getOne(queryWrapper);
//        //修改二次配套表状态
//        LambdaUpdateWrapper<MsSecondMatchInfo> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.set(MsSecondMatchInfo::getStatus, "6");
//        updateWrapper.eq(MsSecondMatchInfo::getWmsDeliveryPlanId, msSecondMatchInfo.getWmsDeliveryPlanId());
//        updateWrapper.eq(MsSecondMatchInfo::getStatus, "5");
//        msSecondMatchInfoService.update(updateWrapper);
//        List<CemopXmlDTO> cemopXmlDTOList = new ArrayList<>();
//        HashMap map = new HashMap<>();
//        map.put("MOM_DELIVERY_PLAN_ID", msSecondMatchInfo.getWmsDeliveryPlanId());
//        map.put("MOM_ASS_MATERIAL_RTW_SM_ID", wmsReturnApply.getWmsReturnApplyId());
//        CemopXmlDTO tableDTO = cemopXmlUtil.createTableDTO("MOM_ASS_MATERIAL_RECEIVE", map);
//        cemopXmlDTOList.add(tableDTO);
//        cemopXmlDTO.setCemopXmlDTOList(cemopXmlDTOList);
//        JSONObject xml = cemopXmlUtil.createXml(cemopXmlDTO);
//        if (xml == null) {
//            log.error("生成XML失败！");
//            return new ResponseMsg<>().setResponseBody(null).setMessage("生成XML失败").setRetCode("500");
//        }
//        return new ResponseMsg<>().setMessage("101库存同意物料二次配套通知装配成功").setResponseBody("");
//    }
//
//    /**
//     * 101库存驳回物料二次配套通知装配
//     * @param msSecondMatchInfo
//     * @return
//     */
//    @Override
//    public ResponseMsg<Object> sendRejectSecondMatch(MsSecondMatchInfo msSecondMatchInfo) {
//        log.info("101库存驳回物料二次配套通知装配数据" + msSecondMatchInfo);
//        LambdaUpdateWrapper<MsSecondMatchInfo> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(MsSecondMatchInfo::getStatus,"5");
//        updateWrapper.eq(MsSecondMatchInfo::getWmsDeliveryPlanId, msSecondMatchInfo.getWmsDeliveryPlanId());
//        updateWrapper.set(MsSecondMatchInfo::getStatus,"7");
//        msSecondMatchInfoService.update(updateWrapper);
//        return new ResponseMsg<>().setMessage("101库存驳回物料二次配套通知装配成功").setResponseBody("");
//    }


    @Override
    public ResponseMsg<Object> saveCemopLog(CemopLogDTO cemopLogDTO) {
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(currentDate);
        cemopLogDTO.setCreateDate(dateString);
        //第一次调用就创建表
        if ("创建日志表".equals(cemopLogDTO.getLogType())) {
            String sql = "CREATE TABLE \"cemop_log\" (\n" +
                    "  id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
                    "  \"receive_data_url\" text(100),\n" +
                    "  \"receive_data\" text(3000),\n" +
                    "  \"send_data_url\" text(100),\n" +
                    "  \"send_data\" text(3000),\n" +
                    "  \"log_type\" text(20),\n" +
                    "  \"Interface_name\" text(100),\n" +
                    "  \"Interface_addr\" text(100),\n" +
                    "  \"log_level\" text(50),\n" +
                    "  \"log_area\" text(50),\n" +
                    "  \"log_platform\" text(50),\n" +
                    "  \"create_date\" text(50)\n" +
                    ");";
            sqliteUtil.executeSql(sql);
            sql = "CREATE TABLE \"cemop_log_his\" (\n" +
                    "  id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
                    "  \"receive_data_url\" text(100),\n" +
                    "  \"receive_data\" text(3000),\n" +
                    "  \"send_data_url\" text(100),\n" +
                    "  \"send_data\" text(3000),\n" +
                    "  \"log_type\" text(20),\n" +
                    "  \"Interface_name\" text(100),\n" +
                    "  \"log_level\" text(50),\n" +
                    "  \"log_area\" text(50),\n" +
                    "  \"log_platform\" text(50),\n" +
                    "  \"create_date\" text(50)\n" +
                    ");";
            sqliteUtil.executeSql(sql);
        } else {
            String sql = "INSERT INTO cemop_log(" +
                    "receive_data_url," +
                    "receive_data," +
                    "send_data_url," +
                    "send_data," +
                    "log_type," +
                    "interface_name," +
                    "log_level," +
                    "log_area," +
                    "log_platform," +
                    "create_date)";
            sql += "VALUES('" + cemopLogDTO.getReceiveDataUrl() + "',";
            sql += "'" + cemopLogDTO.getReceiveData() + "',";
            sql += "'" + cemopLogDTO.getSendDataUrl() + "',";
            sql += "'" + cemopLogDTO.getSendData() + "',";
            sql += "'" + cemopLogDTO.getLogType() + "',";
            sql += "'" + cemopLogDTO.getInterfaceName() + "',";
            sql += "'" + cemopLogDTO.getLogLevel() + "',";
            sql += "'" + cemopLogDTO.getLogArea() + "',";
            sql += "'" + cemopLogDTO.getLogPlatform() + "',";
            sql += "'" + cemopLogDTO.getCreateDate() + "')";
            sqliteUtil.executeSql(sql);
            String sql1 = "INSERT INTO cemop_log_his(" +
                    "receive_data_url," +
                    "receive_data," +
                    "send_data_url," +
                    "send_data," +
                    "log_type," +
                    "interface_name," +
                    "log_level," +
                    "log_area," +
                    "log_platform," +
                    "create_date)";
            sql1 += "VALUES('" + cemopLogDTO.getReceiveDataUrl() + "',";
            sql1 += "'" + cemopLogDTO.getReceiveData() + "',";
            sql1 += "'" + cemopLogDTO.getSendDataUrl() + "',";
            sql1 += "'" + cemopLogDTO.getSendData() + "',";
            sql1 += "'" + cemopLogDTO.getLogType() + "',";
            sql1 += "'" + cemopLogDTO.getInterfaceName() + "',";
            sql1 += "'" + cemopLogDTO.getLogLevel() + "',";
            sql1 += "'" + cemopLogDTO.getLogArea() + "',";
            sql1 += "'" + cemopLogDTO.getLogPlatform() + "',";
            sql1 += "'" + cemopLogDTO.getCreateDate() + "')";
            sqliteUtil.executeSql(sql1);
        }
        return new ResponseMsg<>().setResponseBody("执行成功");
    }

    /**
     * 创建本地表
     *
     * @param localLogDTO
     * @return
     */
    @Override
    public ResponseMsg<Object> saveLocalLog(LocalLogDTO localLogDTO) {
//        Date currentDate = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String dateString = sdf.format(currentDate);
//        localLogDTO.setCreateTime(dateString);
//        //第一次调用就创建表
//        if ("create".equals(localLogDTO.getLogType())) {
//            String sql = "CREATE TABLE \"local_log\" (\n" +
//                    "  id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
//                    "  \"level\" text(100),\n" +
//                    "  \"logger_name\" text(3000),\n" +
//                    "  \"message\" text(100),\n" +
//                    "  \"exception\" text(3000),\n" +
//                    "  \"create_time\" text(50),\n" +
//                    "  \"method\" text(100),\n" +
//                    "  \"ip_address\" text(100),\n" +
//                    "  \"request_param\" text(50),\n" +
//                    "  \"response_param\" text(50)\n" +
//                    ");";
//            sqliteUtil.executeSql(sql);
//            sql = "CREATE TABLE \"local_log_his\" (\n" +
//                    "  id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
//                    "  \"level\" text(100),\n" +
//                    "  \"logger_name\" text(3000),\n" +
//                    "  \"message\" text(100),\n" +
//                    "  \"exception\" text(3000),\n" +
//                    "  \"create_time\" text(50),\n" +
//                    "  \"method\" text(100),\n" +
//                    "  \"ip_address\" text(100),\n" +
//                    "  \"request_param\" text(50),\n" +
//                    "  \"response_param\" text(50)\n" +
//                    ");";
//            sqliteUtil.executeSql(sql);
//        } else {
//            String sql = "INSERT INTO local_log(" +
//                    "level," +
//                    "logger_name," +
//                    "message," +
//                    "exception," +
//                    "create_time," +
//                    "method," +
//                    "ip_address," +
//                    "request_param," +
//                    "response_param)";
//            sql += "VALUES('" + localLogDTO.getLevel() + "',";
//            sql += "'" + localLogDTO.getLoggerName() + "',";
//            sql += "'" + localLogDTO.getMessage() + "',";
//            sql += "'" + localLogDTO.getException() + "',";
//            sql += "'" + localLogDTO.getCreateTime() + "',";
//            sql += "'" + localLogDTO.getMethod() + "',";
//            sql += "'" + localLogDTO.getIpAddress() + "',";
//            sql += "'" + localLogDTO.getRequestParam() + "',";
//            sql += "'" + localLogDTO.getResponseParam() + "')";
//            sqliteUtil.executeSql(sql);
//            String sql1 = "INSERT INTO local_log_his(" +
//                    "level," +
//                    "logger_name," +
//                    "message," +
//                    "exception," +
//                    "create_time," +
//                    "method," +
//                    "ip_address," +
//                    "request_param," +
//                    "response_param)";
//            sql1 += "VALUES('" + localLogDTO.getLevel() + "',";
//            sql1 += "'" + localLogDTO.getLoggerName() + "',";
//            sql1 += "'" + localLogDTO.getMessage() + "',";
//            sql1 += "'" + localLogDTO.getException() + "',";
//            sql1 += "'" + localLogDTO.getCreateTime() + "',";
//            sql1 += "'" + localLogDTO.getMethod() + "',";
//            sql1 += "'" + localLogDTO.getIpAddress() + "',";
//            sql1 += "'" + localLogDTO.getRequestParam() + "',";
//            sql1 += "'" + localLogDTO.getResponseParam() + "')";
//            sqliteUtil.executeSql(sql1);
//        }


        return new ResponseMsg<>().setResponseBody("执行成功");
    }


  /*  @Scheduled(cron = "0 0 2 * * ?")
    public void deleteCemopLog() {
        String sql = "DELETE \n" +
                "FROM\n" +
                "  cemop_log \n" +
                "WHERE\n" +
                "  strftime( '%s', 'now' ) - strftime( '%s', create_data ) > 90 * 24 * 60 * 60";
        sqliteUtil.executeSql(sql);
        String sql1 = "DELETE \n" +
                "FROM\n" +
                "  cemop_log_his \n" +
                "WHERE\n" +
                "  strftime( '%s', 'now' ) - strftime( '%s', create_data ) > 1080 * 24 * 60 * 60";
        sqliteUtil.executeSql(sql1);
    }*/

    @Override
    public ResponseMsg<Object> getLogPage(CemopLogDTO cemopLogDTO) {
        String sql = "SELECT\n" +
                "  id,\n" +
                "  receive_data_url,\n" +
                "  receive_data,\n" +
                "  send_data_url,\n" +
                "  send_data,\n" +
                "  log_type,\n" +
                "  Interface_name,\n" +
                "  log_level,\n" +
                "  log_area,\n" +
                "  log_platform,\n" +
                "  create_date \n" +
                "FROM\n" +
                "  cemop_log  where 1=1 ";
        if (cemopLogDTO.getLogType() != null && cemopLogDTO.getLogType() != "") {
            sql += " and log_type = '" + cemopLogDTO.getLogType() + "'";
        }
        if (cemopLogDTO.getLogArea() != null && cemopLogDTO.getLogArea() != "") {
            sql += " and log_area = '" + cemopLogDTO.getLogArea() + "'";
        }
        if (cemopLogDTO.getCreateStartDate() != null && cemopLogDTO.getCreateStartDate() != "" && cemopLogDTO.getCreateEndDate() != null && cemopLogDTO.getCreateEndDate() != "") {
            sql += "AND create_date BETWEEN '" + cemopLogDTO.getCreateStartDate() + "'" + " AND '" + cemopLogDTO.getCreateEndDate() + "'";
        }

        sql += " LIMIT " + cemopLogDTO.getSize() + " OFFSET (" + cemopLogDTO.getCurrent() + " - 1) * " + cemopLogDTO.getSize();
        List<CemopLogDTO> cemopLogDTOS = sqliteUtil.executeSqlQuery(sql);
        String sql1 = " SELECT COUNT(1) AS pageTotal FROM cemop_log where 1=1";
        if (cemopLogDTO.getLogType() != null && cemopLogDTO.getLogType() != "") {
            sql1 += " and log_type = '" + cemopLogDTO.getLogType() + "'";
        }
        if (cemopLogDTO.getLogArea() != null && cemopLogDTO.getLogArea() != "") {
            sql1 += " and log_area = '" + cemopLogDTO.getLogArea() + "'";
        }
        if (cemopLogDTO.getCreateStartDate() != null && cemopLogDTO.getCreateStartDate() != "" && cemopLogDTO.getCreateEndDate() != null && cemopLogDTO.getCreateEndDate() != "") {
            sql1 += " AND create_date BETWEEN '" + cemopLogDTO.getCreateStartDate() + "'" + " AND '" + cemopLogDTO.getCreateEndDate() + "'";
        }
        String pageTotal = sqliteUtil.executeSqlCount(sql1);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("pageTotal", pageTotal);
        map.put("size", cemopLogDTO.getSize());
        map.put("current", cemopLogDTO.getCurrent());
        map.put("data", cemopLogDTOS);
        return new ResponseMsg<>().setResponseBody(map);
    }

    @Override
    public ResponseMsg<Object> receiveSecondMatchAndReturn(JSONObject jsonObject) throws ParseException {
        jsonObject.put("description","CEMOP系统现场正常退库与二次配套");
        CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.SECOND_MATCH_AND_RETURN.getCode());
        List<SecondMatchAndReturnDTO> secondMatchAndReturnDTOS = cemopDownDTO.getSecondMatchAndReturnDTOS();
        log.info("处理完成后的数据" + secondMatchAndReturnDTOS);
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            //通过类型判断怎么操作
            for (SecondMatchAndReturnDTO secondMatchAndReturnDTO : secondMatchAndReturnDTOS) {
                if (secondMatchAndReturnDTO.getOprteTypCd().equals("2")) {
                    WmsDeliveryPlan wmsDeliveryPlan = wmsDeliveryPlanService.getById(secondMatchAndReturnDTO.getMomWmsDeliveryPlanId());
                    wmsDeliveryPlan.setQualityCode(secondMatchAndReturnDTO.getQltyEcd());
                    wmsDeliveryPlan.setSubstituteCode(secondMatchAndReturnDTO.getOrglFormEcd());
                    wmsDeliveryPlan.setAttribute13(secondMatchAndReturnDTO.getCreateTm());
                    wmsDeliveryPlan.setAttribute12(secondMatchAndReturnDTO.getSndpkQty());
                    wmsDeliveryPlan.setAttribute11(secondMatchAndReturnDTO.getReceiveShop());
                    wmsDeliveryPlan.setAttribute10Desc(secondMatchAndReturnDTO.getMomWmsDeliveryBackId());
                    wmsDeliveryPlan.setAttribute9(secondMatchAndReturnDTO.getFoudrNo());
                    wmsDeliveryPlan.setAttribute14("1");
                    wmsDeliveryPlan.setDeliveryStatus("4");
                    log.info("交接单的数据" + wmsDeliveryPlan);
                    wmsDeliveryPlanService.updateById(wmsDeliveryPlan);
                    //创建退库单的数据
                    WmsReturnApply wmsReturnApply = new WmsReturnApply();
                    wmsReturnApply.setWmsReturnApplyId(IdUtil.simpleUUID());
                    wmsReturnApply.setWmsDeliveryPlanId(secondMatchAndReturnDTO.getMomWmsDeliveryPlanId());
                    wmsReturnApply.setReturnType("1");
                    wmsReturnApply.setItemCode(secondMatchAndReturnDTO.getMtlsEcd());
                    wmsReturnApply.setQualityCode(secondMatchAndReturnDTO.getQltyEcd());
                    wmsReturnApply.setBillNo(secondMatchAndReturnDTO.getReceiveShop());
    //                wmsReturnApply.setMesCheckQualiticationId(secondMatchAndReturnDTO.getCERTIFICATE_NO());
                    wmsReturnApply.setLastUpdateDate(fmt.parse(secondMatchAndReturnDTO.getCreateTm()));
                    wmsReturnApply.setReturnQty(new BigDecimal(secondMatchAndReturnDTO.getSndpkQty()));
                    wmsReturnApply.setLastUpdatedBy(secondMatchAndReturnDTO.getFoudrNo());
                    wmsReturnApply.setRejectReason(secondMatchAndReturnDTO.getRemrkDesc());
                    log.info("退库单数据" + wmsReturnApply);
                    wmsReturnApplyService.save(wmsReturnApply);
                    //修改AO物料配套信息
                    if (wmsDeliveryPlan.getAttribute1() != null && wmsDeliveryPlan.getAttribute1() != "") {
                        LambdaUpdateWrapper<MsAoMatchInfo> updateWrapper = new LambdaUpdateWrapper<>();

                        updateWrapper.set(MsAoMatchInfo::getLastUpdateDate, fmt.parse(secondMatchAndReturnDTO.getCreateTm()));
                        BigDecimal bigDecimal=new BigDecimal(secondMatchAndReturnDTO.getSndpkQty());
                        updateWrapper.set(MsAoMatchInfo::getReturnQty,bigDecimal);
                        updateWrapper.in(MsAoMatchInfo::getMsAoMatchInfoId, wmsDeliveryPlan.getAttribute1());
                        log.info("修改matchInfoId" + wmsReturnApply);
                        iMsAoMatchInfoNewService.update(updateWrapper);
                    }
                } else if (secondMatchAndReturnDTO.getOprteTypCd().equals("1")) {
                    WmsDeliveryPlan wmsDeliveryPlan = wmsDeliveryPlanService.getById(secondMatchAndReturnDTO.getMomWmsDeliveryPlanId());
                    wmsDeliveryPlan.setAttribute13(secondMatchAndReturnDTO.getCreateTm().toString());
                    wmsDeliveryPlan.setAttribute12(secondMatchAndReturnDTO.getSndpkQty());
                    //更新交接单 MS_AO_MATCH_INFO
                    wmsDeliveryPlanService.updateById(wmsDeliveryPlan);
                    //更新MS_AO_MATCH_INFO配套结果表
                    cemopMapper.materialSecondMatchInfo(secondMatchAndReturnDTO.getMomWmsDeliveryPlanId(), secondMatchAndReturnDTO.getSndpkQty());
                    //插入二次配套表 MS_SECOND_MATCH_INFO
                    MsSecondMatchInfo msSecondMatchInfo = new MsSecondMatchInfo();
                    msSecondMatchInfo.setMsSecondMatchInfoId(secondMatchAndReturnDTO.getMomWmsDeliveryBackId());
                    msSecondMatchInfo.setWmsDeliveryPlanId(secondMatchAndReturnDTO.getMomWmsDeliveryPlanId());
                    msSecondMatchInfo.setSecondApplyUsercode(secondMatchAndReturnDTO.getFoudrNo());
                    msSecondMatchInfo.setMatchDate(fmt.parse(secondMatchAndReturnDTO.getCreateTm()));
                    BigDecimal secondMatchQty = new BigDecimal(secondMatchAndReturnDTO.getSndpkQty());
                    msSecondMatchInfo.setSecondMatchQty(secondMatchQty);
                    msSecondMatchInfo.setORGL_FORM_ECD(secondMatchAndReturnDTO.getOrglFormEcd());
                    msSecondMatchInfo.setHNDOVR_BLL_ECD(secondMatchAndReturnDTO.getHndovrBllEcd());
                    msSecondMatchInfo.setOPRTE_TYP_CD(secondMatchAndReturnDTO.getOprteTypCd());
                    msSecondMatchInfo.setSTUS_CD(secondMatchAndReturnDTO.getStusCd());
                    msSecondMatchInfo.setMODLS_ECD(secondMatchAndReturnDTO.getModlsEcd());
                    msSecondMatchInfo.setBCH_NO(secondMatchAndReturnDTO.getBchNo());
                    msSecondMatchInfo.setBEG_SORTIE_NO(secondMatchAndReturnDTO.getBegSortieNo());
                    msSecondMatchInfo.setEXPIRY_SORTIE_NO(secondMatchAndReturnDTO.getExpirySortieNo());
                    msSecondMatchInfo.setAO_ECD(secondMatchAndReturnDTO.getAoEcd());
                    msSecondMatchInfo.setMTLS_ECD(secondMatchAndReturnDTO.getMtlsEcd());
                    msSecondMatchInfo.setQLTY_ECD(secondMatchAndReturnDTO.getQltyEcd());
                    msSecondMatchInfo.setHTBL_ECD(secondMatchAndReturnDTO.getHtbllEcd());
                    msSecondMatchInfo.setREMRK_DESC(secondMatchAndReturnDTO.getRemrkDesc());
                    msSecondMatchInfo.setRECEIVE_SHOP(secondMatchAndReturnDTO.getReceiveShop());
                    msSecondMatchInfo.setFOUDR_NO(secondMatchAndReturnDTO.getFoudrNo());
                    msSecondMatchInfo.setCREATE_TM(fmt.parse(secondMatchAndReturnDTO.getCreateTm()));
                    msSecondMatchInfoService.save(msSecondMatchInfo);
                    CemopStockConfirmationDTO cemopStockConfirmationDTO = new CemopStockConfirmationDTO();
                    cemopStockConfirmationDTO.setMomWmsDeliveryBackId(msSecondMatchInfo.getMsSecondMatchInfoId());
                    cemopStockConfirmationDTO.setStusCd(msSecondMatchInfo.getSTUS_CD());
                    cemopStockConfirmationDTO.setAtlstUpdtrNo(msSecondMatchInfo.getFOUDR_NO());
                    this.getStockConfirmation(cemopStockConfirmationDTO);
                }

            }
            jsonObject.put("msg","CEMOP系统现场正常退库与二次配套通知101库存成功");
            jsonObject.put("status","2");
            sendSortBackResult(jsonObject);
            return new ResponseMsg<>().setResponseBody(null).setMessage("CEMOP系统现场正常退库与二次配套通知101库存成功!").setRetCode("200");
        } catch (Exception e) {
            jsonObject.put("status","3");
            jsonObject.put("msg","失败："+e);
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

    /**
     * 101库存确认处理通知CEMOP系统
     *
     * @return
     */
    @Override
    public ResponseMsg<Object> getStockConfirmation(CemopStockConfirmationDTO stockConfirmationDTO) {
        //查询库存确认处理信息
        CemopUploadDTO cemopUploadDTO = new CemopUploadDTO();
        cemopUploadDTO.setCemopStockConfirmationDTO(stockConfirmationDTO);
        jsonToObject = cemopUtil.uploadUtil(cemopUploadDTO, CemopEnum.STOCK_CONFIRMATION.getCode());
        log.info("101库存确认处理通知CEMOP系统" + jsonToObject);
        return new ResponseMsg<>().setResponseBody(jsonToObject).setMessage("101库存确认处理通知CEMOP系统！");
    }
    /**
     * Cemop接口调用结果反馈TXT
     * @return
     */
    @Override
    public ResponseMsg<Object> getSortBackResultTxt(JSONObject jsonObject) {
        try {
            log.info("Cemop接口调用结果反馈TXT" + jsonObject);
            CemopDownDTO cemopDownDTO = cemopUtil.downUtil(jsonObject, CemopEnum.SORT_BACKR_ESULT_TXT.getCode());
            List<CemopSortBackResultTxtDTO> cemopSortBackResultTxtDTOS = cemopDownDTO.getCemopSortBackResultTxtDTOS();
            log.info("解析文件后数据" + cemopSortBackResultTxtDTOS.toString());
            CemopSortBackResultTxtDTO cemopOutboundDTO = cemopSortBackResultTxtDTOS.get(0);
            LambdaUpdateWrapper<InterfaceLog> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(InterfaceLog::getStatus, cemopOutboundDTO.getStatus());
            updateWrapper.set(InterfaceLog::getIsResult, 0);
            updateWrapper.set(InterfaceLog::getCemopMsg, cemopOutboundDTO.getMsg());
            updateWrapper.eq(InterfaceLog::getBKey, cemopOutboundDTO.getBKey());
            interfaceLogService.update(updateWrapper);
            return new ResponseMsg<>().setResponseBody("接收成功").setMessage("101库存确认处理通知CEMOP系统！");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * Cemop接口调用结果反馈TXT
     * @return
     */
    @Override
    public ResponseMsg<Object> getSortBackResultXml(JSONObject jsonObject) throws FileNotFoundException {
        try {
            //获取文件url
            String fileUrl = jsonObject.get("fileUrl").toString();
            List<File> files = cemopXmlUtil.downloadAndExtractXMLFile(fileUrl);
            //解析xml文件，拿到扫码移交内容
            FileInputStream fileInputStream = new FileInputStream(files.get(0));
            XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
            List<Map<String, String>> list = xmlReadUtil.getAttributesByTagName("SORT");
            List<CemopSortBackResultTxtDTO> cemopSortBackResultTxtDTOS = new ArrayList<>();
            for (Map<String, String> map : list) {
                CemopSortBackResultTxtDTO cemopOutboundDTO = new CemopSortBackResultTxtDTO();
                xmlReadUtil.mapToDTO(map, cemopOutboundDTO);
                cemopSortBackResultTxtDTOS.add(cemopOutboundDTO);
            }
            log.info("解析完成后的数据" + cemopSortBackResultTxtDTOS);

            CemopSortBackResultTxtDTO cemopOutboundDTO = cemopSortBackResultTxtDTOS.get(0);
            LambdaUpdateWrapper<InterfaceLog> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(InterfaceLog::getStatus, cemopOutboundDTO.getStatus());
            updateWrapper.set(InterfaceLog::getIsResult, 0);
            updateWrapper.set(InterfaceLog::getCemopMsg, cemopOutboundDTO.getMsg());
            updateWrapper.eq(InterfaceLog::getBKey, cemopOutboundDTO.getBKey());
            interfaceLogService.update(updateWrapper);
            return new ResponseMsg<>().setResponseBody("接收成功").setMessage("101库存确认处理通知CEMOP系统！");
        } catch(Exception e){
            return new ResponseMsg<>().setResponseBody("接收失败").setMessage("101库存确认处理通知CEMOP系统失败！"+e);
        }
    }
    private JSONObject convertToJSONArray(CemopDownDTO cemopDownDTO, JSONObject jsonObject) {
        Map<String, Object> map = new ObjectMapper().convertValue(cemopDownDTO, Map.class);
        map.put("fileUrl", jsonObject);
        JSONObject jsonObject1 = new JSONObject(map);
        return jsonObject1;
    }
    //文件发送 Cemop接口调用结果反馈TXT
    @Async
    @PostMapping("/send")
    public ResponseMsg<Object> sendSortBackResult(JSONObject jsonObject) {
        String url = environment.getProperty("cemopUrl.proxy");
        String cemopUrl = environment.getProperty("cemopUrl.sortBackResult");
        System.out.println("=========================fileSend文件发送地址=============================："+url);
        JSONObject sendData = new JSONObject();
        Map<String, Object> BDataMap = new HashMap<>();
        String IP = null;
        String URI =  (String) jsonObject.get("fileUrl");
        String description = (String) jsonObject.get("description");
        String businessKey = (String) jsonObject.get("businessKey");
        String bKey = IdUtil.simpleUUID();
        sendData.put("bKey",bKey);
        sendData.put("filePath","");//生成的压缩包路径
        sendData.put("fileUrl", "");
        sendData.put("auditMap", "");
        BDataMap.put("fileSendUrl",cemopUrl);//Cemop接口路径
        BDataMap.put("fileSendMsgUrl", "");
        BDataMap.put("bKey", businessKey);
        BDataMap.put("msg", jsonObject.get("msg"));
        BDataMap.put("status", jsonObject.get("status"));
        sendData.put("BData", BDataMap);
        System.out.println("=====================Cemop两网传输调用代理服务器传递参数========================："+sendData.toString());

        String result= com.cac.demo.util.HttpUtil.post(url, sendData.toJSONString());
        System.out.println("=====================Cemop两网传输调用代理服务器返回参数========================："+result);
        interfaceLogService.saveInterfaceLog(description,cemopUrl,URI,result,null,null,businessKey);
        return null;
    }

    @Override
    public ResponseMsg<Object> receiveAoChange(JSONObject jsonObject) {
        log.info("======================Cemop系统AO变更通知101=============================" + jsonObject);
        jsonObject.put("description","Cemop系统AO变更通知101");
        try {
            //解压文件
            String fileUrl = jsonObject.get("fileUrl").toString();
            List<File> files = cemopXmlUtil.downloadAndExtractXMLFiles(fileUrl);
            //解析xml文件，拿到月计划内容（工作包、AO、物料）[AO不变，工作包全变，物料新增三个字段]
            FileInputStream fileInputStream = new FileInputStream(files.get(0));
            XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
            List<Map<String, String>> list2 = xmlReadUtil.getAttributesByTagName("MOM_ASS_AOTASK");
            List<Map<String, String>> list3 = xmlReadUtil.getAttributesByTagName("MOM_ASS_SETOUT_MATERIAL");
            List<MomAssAOTaskDTO> momAssAOTaskDTOS = new ArrayList<>();
            List<MomAssSetoutMaterialDTO> momAssSetoutMaterialDTOS = new ArrayList<>();
            //AO包
            for (Map<String, String> map : list2) {
                MomAssAOTaskDTO momAssAOTaskDTO = new MomAssAOTaskDTO();
                xmlReadUtil.mapToDTO(map, momAssAOTaskDTO);
                momAssAOTaskDTOS.add(momAssAOTaskDTO);
            }
            //物料
            for (Map<String, String> map : list3) {
                MomAssSetoutMaterialDTO momAssSetoutMaterialDTO = new MomAssSetoutMaterialDTO();
                xmlReadUtil.mapToDTO(map, momAssSetoutMaterialDTO);
                momAssSetoutMaterialDTOS.add(momAssSetoutMaterialDTO);
            }
            //新增或修改AO分拣任务
            for (MomAssAOTaskDTO momAssAOTask : momAssAOTaskDTOS) {
                LambdaQueryWrapper<MsTaskAo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(MsTaskAo::getMsTaskAoId, momAssAOTask.getMOM_ASS_AOTASK_ID());
                MsTaskAo msTaskAo = msTaskAoMapper.selectOne(queryWrapper);
                WmsInvOutBillH wmsInvOutBillH = new WmsInvOutBillH();
                wmsInvOutBillH.setWmsInvOutBillHId(momAssAOTask.getMOM_ASS_AOTASK_ID());
                wmsInvOutBillH.setProductCode(momAssAOTask.getMODLS_ECD());
                wmsInvOutBillH.setBatchNo(momAssAOTask.getBCH_NO());
                wmsInvOutBillH.setStartLotNo(momAssAOTask.getSORTIE_NO());
                wmsInvOutBillH.setAoNo(momAssAOTask.getAO_NO());
                wmsInvOutBillHMapper.insert(wmsInvOutBillH);
                //修改AO信息
                LambdaUpdateWrapper<MsTaskAo> updateWrapper = new LambdaUpdateWrapper<>();
                if (momAssAOTask.getMODLS_ECD() != null)
                    updateWrapper.set(MsTaskAo::getProductCode, momAssAOTask.getMODLS_ECD());
                if (momAssAOTask.getBCH_NO() != null)
                    updateWrapper.set(MsTaskAo::getBatchNo, momAssAOTask.getBCH_NO());
                if (momAssAOTask.getPLAN_ID() != null)
                    updateWrapper.set(MsTaskAo::getPlanId, momAssAOTask.getPLAN_ID());
                if (momAssAOTask.getSORTIE_NO() != null)
                    updateWrapper.set(MsTaskAo::getStartPlaneNo, momAssAOTask.getSORTIE_NO());
                if (momAssAOTask.getMANUFA_BCPLT_ECD() != null)
                    updateWrapper.set(MsTaskAo::getDepartCode, momAssAOTask.getMANUFA_BCPLT_ECD());
                if (momAssAOTask.getWKSTTN_ECD() != null)
                    updateWrapper.set(MsTaskAo::getPackageCode, momAssAOTask.getWKSTTN_ECD());
                if (momAssAOTask.getAO_NO() != null)
                    updateWrapper.set(MsTaskAo::getAoCode, momAssAOTask.getAO_NO());
                if (momAssAOTask.getAO_NAME() != null)
                    updateWrapper.set(MsTaskAo::getAoName, momAssAOTask.getAO_NAME());
                if (momAssAOTask.getPLAN_START_DATE() != null)
                    updateWrapper.set(MsTaskAo::getRequiredTime, momAssAOTask.getPLAN_START_DATE());
                updateWrapper.set(MsTaskAo::getLastUpdateDate, new Date());

                if (momAssAOTask.getSYS_MADE_CENTER() != null)
                    updateWrapper.set(MsTaskAo::getStation, momAssAOTask.getSYS_MADE_CENTER());

                updateWrapper.eq(MsTaskAo::getMsTaskAoId, momAssAOTask.getMOM_ASS_AOTASK_ID());

                iMsTaskAoService.update(updateWrapper);

                LambdaQueryWrapper<MsAoMatchInfo> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(MsAoMatchInfo::getMsTaskAoId, momAssAOTask.getMOM_ASS_AOTASK_ID());
                List<MsAoMatchInfo> msAoMatchInfos = iMsAoMatchInfoNewService.list(queryWrapper1);

                //找到变更前的所有物料
                LambdaQueryWrapper<MsAoMatchBill> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(MsAoMatchBill::getMsTaskAoId, momAssAOTask.getMOM_ASS_AOTASK_ID());
                //加上机型等
                List<MsAoMatchBill> msAoMatchBills = iMsAoMatchBillService.list(queryWrapper2);
                //变更后的所有物料
                List<MomAssSetoutMaterialDTO> momassSetoutMaterialDTOS2 = momAssSetoutMaterialDTOS.stream().filter(m -> m.getMOM_ASS_AOTASK_ID().equals(momAssAOTask.getMOM_ASS_AOTASK_ID())).collect(Collectors.toList());
                //判断这些物料是否在变更后的物料列表中，如果变更后物料不存在，则判断是否已经分拣
                for (MsAoMatchBill msAoMatchBill : msAoMatchBills) {
                    MomAssSetoutMaterialDTO momAssSetoutMaterialDTO = momassSetoutMaterialDTOS2.stream().filter(m -> m.getMOM_ASS_SETOUT_MATERIAL_ID().equals(msAoMatchBill.getMsAoMatchBillId())).findFirst().orElse(null);
                    //判断变更后物料是否存在，如果为空则表示之前存在现在不存在，需要处理历史数据
                    if (Objects.isNull(momAssSetoutMaterialDTO)) {
                        //此物料不存在，判断是否已经分拣
                        MsAoMatchInfo msAoMatchInfo = msAoMatchInfos.stream().filter(i -> i.getMsAoMatchBillId().equals(msAoMatchBill.getMsAoMatchBillId())).findFirst().orElse(null);
                        if (msAoMatchInfo != null && msAoMatchInfo.getIsSort().equals("Y")) {
                            //物料已经分拣，需要生成拆包任务
                            msAoMatchInfoMapper.updateMsAoMatchInfo(msAoMatchInfo.getMsAoMatchInfoId());
                        }
                        else if (msAoMatchInfo != null && msAoMatchInfo.getIsSort().equals("N")){
                            //物料没有分拣但是已经配套，直接删除需求物料以及配套占用信息
                            msAoMatchInfoMapper.deleteMsAoMatchInfo(msAoMatchInfo.getMsAoMatchInfoId());
                        }
                    }else{
                        //物料没有变更不需要处理
                        momassSetoutMaterialDTOS2.remove(momAssSetoutMaterialDTO);
                    }
                }

                //变更后新增的物料直接插入物料表即可
                for (MomAssSetoutMaterialDTO m : momassSetoutMaterialDTOS2) {
                    Map<String, String> materialTypeMapping = new HashMap<>();
                    materialTypeMapping.put("零件", "M");
                    materialTypeMapping.put("配套零件", "M");
                    materialTypeMapping.put("零部件", "M");
                    materialTypeMapping.put("成品", "F");
                    materialTypeMapping.put("配套成品", "F");
                    materialTypeMapping.put("成品虚件", "S");
                    materialTypeMapping.put("配套部件", "Z");
                    materialTypeMapping.put("标准件", "Z");
                    String itemType = materialTypeMapping.get(m.getITEM_TYPE());
                    m.setITEM_TYPE(itemType);
                    m.setImportGroupNo(msTaskAo.getImportGroupNo());
                    //没有分拣的物料直接删除需求物料数据，重新插入
                    msAoMatchBillMapper.insertOrUpdateAoMatchBill(m);
                }
            }
            jsonObject.put("msg","Cemop系统AO变更通知101成功");
            jsonObject.put("status","2");
//            sendSortBackResult(jsonObject);
            return null;
        } catch (FileNotFoundException e) {
            jsonObject.put("msg","Cemop系统AO变更通知101失败："+e);
            jsonObject.put("status","3");
            sendSortBackResult(jsonObject);
            throw new RuntimeException(e);
        }
    }

}
